Since you've already learned Web design in 4 minutes, it's time to dive into the Web's main programming language: JavaScript.
JavaScript in 14 minutes
I believe you are using this:
If this information is correct, let's get started.
Console tool
Your browser comes with a developer console that allows you to type JavaScript directly in this webpage.
Since you're using Apple Safari:
- Go to Preferences with command+,
- Go to the Advanced tab
- Enable Show Develop menu in menu bar
- Open the JavaScript console option+command+C
Let's see if it works!
In the console, type (or paste) the following, and press Enter
alert('Hello World!')
Great job!
You've just used alert()
, a native JavaScript function that comes with every browser.
But what have you done exactly?
Functions concept
You've called the alert()
function with the 'Hello World!'
argument.
You have basically done 4 things:
alert('Hello World!')
alert('Hello World!')
alert('Hello World!')
alert('Hello World!')
Sometimes, there's no argument.
Sometimes, there's multiple arguments.
Most of them are required, but some of them can be optional.
In this case, alert()
requires only one argument.
But what type of argument is that?
Strings type
When you handle text, you're using strings, which are a series of characters. In our case, we used a series of 12 characters: Hello World!
. This includes all lowercase and uppercase letters, the space, and the exclamation point.
To define where the string starts and where it ends, you need to wrap it in quotes (either single '
or double "
).
When you defined the 'Hello World!'
string:
- you typed a single quote
- you typed the 12 characters
- you typed another single quote
What if you wanted to deal with numbers instead?
Numbers type
Like any other programming language, JavaScript can handle numbers.
These numbers can be big or small, with or without decimals, combined through numeric operations…
Type or paste the following snippet in your console:
alert(9+5 * 3)
Perfect!
Notice a few things:
- you're using the
+
and*
operators - the mathematical order is respected: first
5 * 3
is calculated, then9 + 15
- the spaces around the
*
symbol don't affect the output ; they're just here to help us (humans!) read the code.
You can find numbers in lots of places.
Browser dimensions info
Numbers are everywhere! Especially in a browser.
For example, your current browser window has a certain width that you can access with JavaScript.
Type the following:
alert(window.innerWidth)
Wonderful!
This means your browser's window is 1680 pixels wide.
As you would have guessed, window.innerHeight
exists as well, as does window.scrollY
, which gives you the current scroll position.
But what is window
exactly?
Objects type
window
is a JavaScript object.
innerWidth
is a property of the window
object.
To access this property, you used a dot .
to specify you wanted the innerWidth
that exists within the window
object.
The JavaScript object is basically a type that contains other things.
For example, window
also has:
window.origin
which is a stringwindow.scrollY
which is a numberwindow.location
which is an object
If window
is an object that contains location
which is another object, this means that JavaScript objects support…
Nesting info
A property of an object can be an object itself (inception!).
Since window.location
is an object too, it has properties of its own. To access these properties, just add another dot .
and the name of the property.
For example, the href
property exists:
alert(window.location.href)
Awesome!
You just displayed the full URL of this webpage. This is because:
window
is an objectlocation
is an objecthref
is a string
There's no limit to how deeply objects can be nested.
There's also no limit to the number of properties an object can have.
As we've seen, the properties of an object can be of any type: strings, numbers, objects, and even functions. In the latter case, it's called…
Methods info
When an object's property is a function, it's called a method instead.
Actually, the alert()
function we've been using so far is a method of the window
object!
window.alert('OMG')
OMG indeed!
Since window
is the top-level object in the browser, you can access all its properties and methods directly.
That's why typing location.href
is the same as typing window.location.href
.
Or why alert()
is equivalent to window.alert()
.
Objects are useful for grouping several properties under the same name and scope, and defining a hierarchy in the data. It's like a tree, where each branch can have other smaller branches.
But what if you only needed a list of things…
Arrays type
A JavaScript array is a type that can contain multiple values, as if they were in an ordered list.
Let's pass an array of 3 strings to the alert()
function:
alert(['What', 'is', 'up'])
Exactly!
You already know the syntax for calling the alert
function: alert(argument)
.
In this case, the argument you passed is an array with 3 items that you have defined like this:
['What', 'is', 'up']
['What', 'is', 'up']
['What', 'is', 'up']
['What', 'is', 'up']
['What', 'is', 'up']
An array can contain any type of values: strings, numbers, objects, other arrays, and more…
Try out this snippet:
alert([2 + 5, 'samurai', true])
True!
The first item 2 + 5
is a number, while the second one 'samurai'
is a string.
What about the third argument? It's not a string because it's not wrapped in quotes, and it's not a number either.
So what is it?
Booleans type
While strings and numbers have an infinite amount of possible values, a boolean can only be either true
or false
.
By combining the alert()
function and the 3-item array on a single line, it makes our code less readable.
What if we could split the two by moving the array onto its own line?
Variables concept
We can move the array into a variable.
A variable is a container that stores a certain value. It has a name (so you can identify and re-use it), and it has a value (so you can update it later on).
var my_things = [2 + 5, 'samurai', true];
-
my_things
is the name of the variable -
[2 + 5, 'samurai', true]
is the value of the variable
Here's the breakdown:
var
var my_things = [2 + 5, 'samurai', true];
var my_things = [2 + 5, 'samurai', true];
=
var my_things = [2 + 5, 'samurai', true];
var my_things = [2 + 5, 'samurai', true];
var my_things = [2 + 5, 'samurai', true];
This means that my_things
is equal to [2 + 5, 'samurai', true]
.
We can now reinstate the alert
function:
Since we now have two statements, we need to separate them with a semicolon ;
in order to know where one ends and the next one begins.
var my_things = [2 + 5, 'samurai', true];
alert(my_things);
Wonderful!
By storing our array into a variable, we managed to make our code more readable.
Although this my_things
variable contains a list of several things, we might want to deal with only a single item of the list.
To access a specific item of an array, you first need to know its index (or position) within the array. You then need to wrap this index into square brackets.
Can you guess which item is gonna be displayed?
var my_things = [2 + 5, 'samurai', true];
alert(my_things[1]);
You guessed it!
It's the second item that showed up! In programming, indexes start at zero 0
.
my_things[1]
my_things[1]
my_things[1]
my_things[1]
It turns out that variables are objects too! Which means that variables also have properties and methods.
For example, my_things
has a property called length
:
var my_things = [2 + 5, 'samurai', true];
alert(my_things.length);
That's right!
The array has 3 items. You'll see that if you add or remove items in my_things
, this length
value will change accordingly.
While readability and properties are useful, the main point of a variable is that it's editable: you can change the value afterwards!
var my_things = [2 + 5, 'samurai', true];
alert(my_things);
my_things = [2 + 5, 'samurai', true, 'LOVE'];
alert(my_things);
Yep!
Two alert boxes have been displayed, but with different values! That's because between the first call and the second one, the value of my_things
has been updated: a fourth item, the string 'LOVE'
, was added.
Note that the second time we're assigning a value to my_things
, we're not using the var
keyword: it's because we're editing the my_things
variable defined two lines above.
You only use the keyword var
when you're creating a new variable, not when you're editing one.
Do you remember I told you variables had methods too (since they're objects)? Another way to edit an array's value is by using the push()
method:
var my_things = [2 + 5, 'samurai', true];
alert(my_things);
my_things.push('The Button');
alert(my_things);
Fantastic!
The my_things
array ends up with 4 items.
While the push()
method altered the array, others simply return a value:
var my_things = [2 + 5, 'samurai', true];
alert(my_things.includes('ninja'));
No ninja here!
The includes()
method checked if the string 'ninja'
was present in the array. Since it wasn't, the method returned false
, a boolean value.
As a matter of fact, when dealing with booleans, typing the keywords true
or false
is quite rare. Usually, booleans exist as a result of a function call (like includes()
) or a comparison.
Here's a "greater than" comparison:
alert(window.innerWidth > 400)
Great again!
This means your browser window is not wider than 400 pixels.
window.innerWidth > 400
window.innerWidth > 400
window.innerWidth > 400
Just like the +
and *
before, >
is a JavaScript operator.
When you make such a comparison with the "greater than" operator >
, you obtain a boolean value.
Since the result of a comparison only has 2 outcomes (true
or false
), it's useful in cases where your code has to make a decision…
Conditional statements concept
Conditional statements are one of the most important concepts in programming. They allow your code to perform certain commands only if certain conditions are met. These conditions can for example be based on:
- a user's input (is the password entered correct?)
- the current state (is it day or night?)
- the value of a certain element (is this person older than 18?)
For now, let's trigger an alert box only if you happen to be on my domain!
if (window.location.hostname == 'jgthms.com') {
alert('Welcome on my domain! ?')
}
Equal indeed!
We're doing another comparison here, but with the "equal to" operator ==
instead.
if
if (window.location.hostname == 'jgthms.com') {
if (window.location.hostname == 'jgthms.com') {
if (window.location.hostname == 'jgthms.com') {
if (window.location.hostname == 'jgthms.com') {
if (window.location.hostname == 'jgthms.com') {
alert('Welcome on my domain! ?')
}
Since the alert box did appear, it means that the hostname is indeed equal to 'jgthms.com'
!
We've handled the case when the comparison returns true
.
To handle the opposite case, when the hostname isn't 'jgthms.com'
, we can use the "not equal to" operator !=
:
if (window.location.hostname != 'jgthms.com') {
alert('Please come back soon! ?')
}
If you try out this snippet, you'll see that it doesn't trigger anything! (Unless this tutorial has been copied to another domain ?).
What if we wanted to handle both cases simultaneously? We could write two if
statements in a row. But since one statement is the exact opposite of the other, we can combine them with a else
statment:
if (window.location.hostname == 'jgthms.com') {
alert('Welcome on my domain! ?')
} else {
alert('Please come back soon! ?')
}
Still equal!
With this conditional setup, we can be sure that:
- only one of the two alerts will be triggered, but never both
- at least one of the two alerts will be triggered, because we're covering all cases
While else
is useful for covering all remaining cases, sometimes you want to handle more than two cases.
By using else if
you can add intermediate statements and handle multiple cases:
if (window.innerWidth > 2000) {
alert('Big screen! ?')
} else if (window.innerWidth < 600) {
alert('Probably a mobile phone ?')
} else {
alert('Decent size ?')
}
You got it!
As soon as one comparison returns true
, it will be triggered, and all following statements will be ignored. That's why only one alert box showed up!
Conditional statements make use of the keywords if
and else
, followed by a set of parentheses.
This pattern of keyword/parentheses combination also happens to exist for another essential programming concept…
Loops concept
When you want to execute a block of code a certain amount of times, you can use a JavaScript loop.
Can you guess how many alert boxes this snippet will trigger?
for (var i = 0; i < 3; i++) {
alert(i);
}
Three it is!
There were exactly 3 alert boxes! Let's dissect what happened:
-
var i = 0
is the initial state
Before the loop even starts, the variablei
is assigned a value of zero0
. -
i < 3
is the conditional statement
On every iteration of the loop, we check this comparison.
If it'strue
, we execute the code in the block.
If it'sfalse
, we exit the loop.
-
i++
is the increment expression
If the block of code is executed, this expression is executed.
In this case, the value ofi
is incremented by 1.
Here's how you implemented it:
for
for (var i = 0; i < 3; i++) {
for (var i = 0; i < 3; i++) {
for (var i = 0; i < 3; i++) {
for (var i = 0; i < 3; i++) {
for (var i = 0; i < 3; i++) {
for (var i = 0; i < 3; i++) {
for (var i = 0; i < 3; i++) {
for (var i = 0; i < 3; i++) {
for (var i = 0; i < 3; i++) {
alert(i);
}
Let's analyze each iteration of the loop:
Iteration | Value of i |
Test | Trigger the alert? |
---|---|---|---|
1st | 0 | 0 < 3 |
Yes |
2nd | 1 | 1 < 3 |
Yes |
3rd | 2 | 2 < 3 |
Yes |
4th | 3 | 3 < 3 |
No! |
This loop allowed us to repeat an action N times. That's what computers are all about!
Of all the types of variables we've covered so far, there is one in particular worth looping through…
Looping through arrays tool
Arrays are a perfect candidate for loops, because in programming we often want to repeat the same action for each item of an array.
Let's say we wanted to trigger an alert box for each item of an array. While we could write as many alert()
statements as there are items in the array (?), this solution is cumbersome and ineffective! It would be prone to errors, and wouldn't scale at all with bigger arrays.
Since programming languages are here to help us simplify our work, let's figure out a better way. We already know a few things:
- We know how to get an array's length
- We know how to access an array's item by using the index
-
We have access to the variable
i
, which conveniently increments 1 by 1
By combining these informations, we can devise the following snippet:
var my_things = [2 + 5, 'samurai', true];
for (var i = 0; i < my_things.length; i++) {
alert(my_things[i]);
}
In a row!
One by one, the items of the array were displayed in their own alert box.
While using a loop simplifies the process of going through each item of an array, we still had to create a for
block manually and create a new variable i
whose only purpose was to increment after each loop.
I know what you're thinking. "There must be a better way!"
forEach loop tool
Arrays actually have a method called forEach()
, which allows to perform a task for each item in the array:
var my_things = [2 + 5, 'samurai', true];
my_things.forEach(function(item) {
alert(item);
});
Better!
Note a few improvements:
-
There is no
i
variable involved -
We don't need to access the array's
length
-
We don't need to use the index with
my_thing[i]
to access the item
Remember the syntax of the alert()
function? It was alert(argument)
.
If you look carefully, you can see that forEach()
has the exact same syntax! It's forEach(argument)
but where the argument happens to be a function that spans 3 lines.
So far, we've used a few functions and methods:
-
the
alert()
function (or window method) -
the
push()
array method -
the
includes()
array method -
the
forEach()
array method
We know how to call a function, but how do you actually create one?
Creating a custom function info
The power of programming languages is the ability to create your own functions, that fit your needs.
Remember the keyword/parentheses combination that we used for if/else
and for
? Well, guess what: it's almost the same pattern here!
I'm saying "almost" because the only difference is that a function needs a name!
Let's create a function called greet()
, with 1 parameter called name
, and then immediately call it:
function greet(name) {
var message = 'Hey there ' + name;
alert(message);
}
greet('Alex');
Greetings!
You've created your first function! It's a simple one but it can teach you a lot.
Note a few things:
-
the name of the function is
greet
-
the parameter is called
name
: it's like a variable, since it acts as a container for a value -
we're creating a variable called
message
(a string) whose value is'Hey there ' + name
-
what this plus sign
+
does is concatenate (or combine) the two strings to make a single longer one -
we're calling the
alert()
function, and use themessage
variable as parameter -
after having created the function, we're calling it with the argument
'Alex'
If we break it down step by step:
function
function greet(name) {
function greet(name) {
function greet(name) {
name
function greet(name) {
function greet(name) {
function greet(name) {
var message = 'Hey there ' + name;
alert(message);
}
greet('Alex');
Unless we call the greet()
function at the end, nothing happens! That's because the alert()
call is inside the scope of greet()
so it's not triggered unless the parent function greet()
itself is called!
Basically, by creating greet()
, you're only telling the browser: "Hey! I've created this new function. So if at some point I call it, please execute whatever is inside!".
That's why, when you call greet()
at the end, the browser executes its content, which happens to be calling alert()
.
It's important to understand that functions are a 2-step process: creating it first, calling it afterwards.
As a matter of fact, the alert()
function we've used all along was already created beforehand. It just exists somewhere inside your browser.
Anyway, we've already covered a lot in 14 minutes!
So, what's next?
Next steps victory!
Learn JavaScript
We've barely covered the basics here. But don't worry! There are tons of resources available online!
Here are a few free resources I'd recommend:
- Eloquent JavaScript
- freeCodeCamp
- The Modern JavaScript Tutorial
- Mozilla Developer Network
- You Don't Know JS
If you prefer video tutorials, check out these Udemy courses:
If you're in a rush, try this shorter course!
Learn HTML and CSS
JavaScript is only one third of what makes a webpage! You also need to know HTML and CSS.
Luckily, I've created two free references for you to browse through, so you can learn everything each language has to offer!
Learn my CSS framework
I designed this page with Bulma, my free open source CSS framework based on Flexbox. Check it out!
Read my book
I wrote a 44-page PDF called "CSS in 44 minutes" which teaches how to build your own personal webpage from scratch with HTML5 and CSS3.
As a bonus, the book also includes a small chapter on JavaScript in which I talk about functions, conditionals, objects, strings, and even explains how to interact with CSS.
I guess now there's only one thing left to do…