Since you've already learned Web design in 4 minutes, it's time to dive into the Web's main programming language: JavaScript.
---
layout: default
---
Since you've already learned Web design in 4 minutes, it's time to dive into the Web's main programming language: JavaScript. I believe you are using this: If this information is correct, let's get started.JavaScript in 14 minutes
Your browser comes with a developer console that allows you to type JavaScript directly in this webpage.
Since you're using Apple Safari:
Let's see if it works!
In the console, type (or paste) the following, and press Enter
You've just used alert(), a native JavaScript function that comes with every browser.
But what have you done exactly?
You've called the alert() function with the 'Hello World!' parameter.
You have basically done 4 things:
alert('Hello World!')alert('Hello World!')alert('Hello World!')alert('Hello World!')Sometimes, there's no parameter.
Sometimes, there's multiple parameters.
Most of them are required, but some of them can be optional.
In this case, alert() requires only one parameter.
But what type of parameter is that?
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:
What if you wanted to deal with numbers instead?
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:
Notice a few things:
+ and * operators5 * 3 is calculated, then 9 + 15* 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.
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:
{% capture snippet %}{% include snippets/snippet_innerwidth.md %}{% endcapture %} {% include partials/snippet.html contents=snippet %}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?
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 objectIf window is an object that contains location which is another object, this means that JavaScript objects support…
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:
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…
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!
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…
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:
You already know the syntax for calling the alert function: alert(parameter).
In this case, the parameter 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:
{% capture snippet %}{% include snippets/snippet_list.md %}{% endcapture %} {% include partials/snippet.html contents=snippet %}
The first item 2 + 5 is a number, while the second one 'samurai' is a string.
What about the third parameter? It's not a string because it's not wrapped in quotes, and it's not a number either.
So what is it?
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?
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).
{% capture snippet %}{% include snippets/snippet_array.md %}{% endcapture %} {% include partials/snippet.html contents=snippet skipRun=true %}my_things is the name of the variable
[2 + 5, 'samurai', true] is the value of the variable
Here's the breakdown:
varvar 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.
By storing our array into a variable, we managed to make our code more readable.
Although this variables 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?
{% capture snippet %}{% include snippets/snippet_array_index.md %}{% endcapture %} {% include partials/snippet.html contents=snippet %}
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:
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!
{% capture snippet %}{% include snippets/snippet_array_edit.md %}{% endcapture %} {% include partials/snippet.html contents=snippet %}
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:
The my_things array ends up with 4 items.
While the push() method altered the array, others simply return a value:
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:
{% capture snippet %}{% include snippets/snippet_innerwidth_boolean.md %}{% endcapture %} {% include partials/snippet.html contents=snippet %}This means your browser window is not wider than 400 pixels.
window.innerWidth > 400window.innerWidth > 400window.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 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:
For now, let's trigger an alert box only if you happen to be on my domain!
{% capture snippet %}{% include snippets/snippet_if.md %}{% endcapture %} {% include partials/snippet.html contents=snippet %}
We're doing another comparison here, but with the "equal to" operator == instead.
ifif (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 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:
With this conditional setup, we can be sure that:
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:
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…
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?
{% capture snippet %}{% include snippets/snippet_loop.md %}{% endcapture %} {% include partials/snippet.html contents=snippet %}There were exactly 3 alert boxes! Let's dissect what happened:
var i = 0 is the initial statei is assigned a value of zero 0.
i < 3 is the conditional statementtrue, we execute the code in the block.false, we exit the loop.i++ is the increment expressioni is incremented by 1.
Here's how you implemented it:
forfor (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…
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:
i, which conveniently increments 1 by 1
By combining these informations, we can devise the following snippet:
{% capture snippet %}{% include snippets/snippet_loop_array.md %}{% endcapture %} {% include partials/snippet.html contents=snippet %}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!"
Arrays actually have a method called forEach(), which allows to perform a task for each item in the array:
Note a few improvements:
i variable involved
length
my_thing[i] to access the item
Remember the syntax of the alert() function? It was alert(parameter).
If you look carefully, you can see that forEach() has the exact same syntax! It's forEach(parameter) but where the parameter happens to be a function that spans 3 lines.
So far, we've used a few functions and methods:
alert() function (or window method)
push() array method
includes() array method
forEach() array method
We know how to call a function, but how do you actually create one?
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:
You've created your first function! It's a simple one but it can teach you a lot.
Note a few things:
greet
name: it's like a variable, since it acts as a container for a value
message (a string) whose value is 'Hey there ' + name
+ does is concatenate (or combine) the two strings to make a single longer one
alert() function, and use the message variable as parameter
'Alex'
If we break it down step by step:
functionfunction greet(name) {function greet(name) {function greet(name) {namefunction 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?
We've barely covery the basics here. But don't worry! There are tons of resources available online!
Here are a few free resources I'd recommend:
If you prefer video tutorials, check out these Udemy courses:
If you're in a rush, try this shorter course!
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!
I designed this page with Bulma, my free open source CSS framework based on Flexbox. Check it out!
{% include partials/panorama.html class_name="bulma" href="https://bulma.io/" path="bulma-modern-css-framework-flexbox" extension="png" alt="Bulma CSS framework based on Flexbox" width="256" height="160" %}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.
{% include partials/panorama.html class_name="fortyfour" href="https://jgthms.com/css-in-44-minutes-ebook" path="css-in-44-minutes-book-cover" extension="png" alt="CSS in 44 minutes ebook" width="168" height="235" %}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…