Syntax & basics
Naming conventions & linking files
JavaScript files should have a
.js extension. We recommend
keeping all JavaScript files in a
/js folder alongside the
/css folder. Usually, the
primary JavaScript file is named
main.js, and all additional
ones should have a descriptive name.
A JavaScript file is executed as soon as it is loaded. This means
that, if you want to access an element on the page place after the
<script>
tag, JavaScript will not be able to find it and will throw an error.
To avoid this, you place the
<script>
tag at the end of the page, right before the closing
</body> tag.
Advanced: deffer and async
You can keep a cleaner file structure by keeping all your
<script>
tags in the
<head>
tag. You can then specify how and when the script will be loaded
using the
async
and
defer
attributes. The
async
attribute will load the script asynchronously, which means that
the page will continue to load and render while the script is
being loaded. The
defer
attribute will load the script after the page has finished
loading.
Variables & functions
What is a variable?
Variables are used to store a value. This value can be anything,
such as a number, a string (text), an object (structured data), an
array (a list of values), a function, or even an HTML element.
Variables are declared using the
var
keyword, followed by the variable name and an optional initial
value. The variable name should serve as a hint as to what the
variable is used for. The initial value is optional, and if not
provided, the variable will be assigned the value of
undefined.
You should define a variable only once. If you need to reassign a
variable, you can use the same syntax as described above, but
without the
var
keyword.
// Declare a variable
var projectCount = 12;
// Reassign a variable
projectCount = 13;
// Declare a variable without assigning a value
var projectTitle;
// Assign a value later on
projectTitle = "Project Name";
// → the "" denotes a string, some text that
// should not by read as code by the browser.
You can combine variables together to create new variables using the
+
operator. This is useful when you want to create a new variable that
is a combination of two or more existing variables. The same
operator can naturally also be used to perform arythmetic
operations.
var projectName = "Project Name";
var projectCount = 12;
// Combine the two variables to create a new one
var projectTitle = projectName + " - " + projectCount + " projects";
// → The value of the projectTitle variable is now
// "Project Name - 12 projects"
Advanced: mutable vs immutable
The
var
declaration has become replaced by two new ones:
let
and
const. The
let
declaration is used to declare a mutable variable, which means its
value can be reassigned. Conversely, the
const
declaration is used to declare an immutable variable, which means
its value cannot be reassigned. The advantage of using
const
is that you can't accidentally reassign a value to a variable,
which can lead to bugs.
What are function?
Functions are reusable blocks of code that perform a specific task.
They are how your code does something. You can think of it as
a mathematical formula: it takes some input, performs some
calculations, and returns a result. To declare a function, you use
the
function
keyword, followed by the function name and a set of parentheses
containing the function's parameters or inputs (comma-separated),
and lastly a set of curly braces containing the function's code. To
call, or execute, the function, you simply use the function name
followed by a set of parentheses containing the function's inputs.
The parameters or inputs are optional. They are usefull to declare some variables that will be used inside the function.
// Declare a function taking the name variable as input
function sayHello(name) {
// The function's code goes here
alert("Hello " + name + "!");
}
// Call the function with the string "John" as input
sayHello("John");
Manipulate HTML elements
Assign HTML elements to variables
You can use HTML elements as variables, which comes in handy when
you want to access or alter the class, content, or attributes of an
element. To assign an element to a variable, you need a way to
select it. Coming from CSS, the simplest way to do this is to use
the
document.querySelector()
method. This method takes a CSS selector as input, and returns the
first element that matches the selector. If no element matches the
selector, it returns
null.
<div class="project-wrapper">
<h2 class="project-title">Project Name</h2>
<p class="project-description">Lorem ipsum…</p>
<img id="hero-image" src="assets/media/placeholder-a.jpg" />
</div>
// Select the first element with the class "project-wrapper"
var projectWrapper = document.querySelector(".project-wrapper");
// Select the first element with the id "hero-image"
var heroImage = document.querySelector("#hero-image");
// Select the first header 2 element with the class "project-title"
var projectTitle = document.querySelector("h2.project-title");
// Select the first paragraph Element
var projectDescription = document.querySelector("p");
// See the results in your browser's console
console.log(projectWrapper);
console.log(heroImage);
console.log(projectTitle);
console.log(projectDescription);
Change an HTML element's class
A simple way to make an HTML element interactive is by adding or
removing a class. This lets you style the interaction in CSS, which
is much easier than designing the interaction using JavaScript. To
add a class, you use the
element.classList
property. To add a class, use the
.add("class-name")
method, and the remove one, the
.remove("class-name")
method. You can also toggle the class using the
.toggle("class-name")
method.
span {
color: black;
display: block;
cursor: pointer;
text-align: center;
margin-block: 1rem;
transform: scale(1) rotate(0turn);
transition: transform 450ms ease-in-out, color 450ms ease-in-out;
}
span.active {
color: deeppink;
transform: scale(2) rotate(2turn);
}
+
// Assign the elements to the variables
var span1 = document.querySelector("span");
var span2 = document.querySelector("#span-2");
var span3 = document.querySelector("#span-3");
span1.onclick = function () {
// Add the "active" class to the element
span1.classList.add("active");
console.log("Class added to span 1");
}
span2.onclick = function () {
// Remove the "active" class from the element
span2.classList.remove("active");
console.log("Class removed from span 2");
}
span3.onclick = function () {
// Toggle the "active" class on the element
span3.classList.toggle("active");
console.log("Class toggled on span 3");
}
Arrays and iteration
Arrays let you store multiple values in a single variable. Think of
it as a list of values, where you can store numbers, project names,
or even HTML elements. To create an array, you use the
[x, y, z]
syntax, a list of values separated by commas surrounded by square
brackets. Every value in an array can be accessed by its
index, its position in the array. The first index is 0, the second is 1,
and so on. To get the value stored at a desired index in an array,
you add the index surrounded by square brackets to the variable name
containing the array.
// Create an array with three values
var projectNames = ["Project Name", "Project Name 2", "Project Name 3"];
// Get the value stored at the first position
var projectName1 = projectNames[0];
// Get the value stored at the third position
var projectName3 = projectNames[2];
alert('"' + arrayProjectName1 + '" and "' + arrayProjectName3 + '"');
Just like the
document.querySelector()
returns the first element that matches the selector, the
document.querySelectorAll()
method returns an array containing all the elements that match the
selector.
<div class="project-wrapper">
<div class="project">
<h2 class="project-title">Project Name</h2>
<img src="assets/media/placeholder-a.jpg" />
</div>
<div class="project">
<h2 class="project-title">Project Name 2</h2>
<img src="assets/media/placeholder-b.jpg" />
</div>
<div class="project">
<h2 class="project-title">Project Name 3</h2>
<img src="assets/media/placeholder-c.jpg" />
</div>
<div class="project">
<h2 class="project-title">Project Name 3</h2>
<img src="assets/media/placeholder-d.jpg" />
</div>
</div>
+
// Select all the elements with the class "project"
var projects = document.querySelectorAll(".project");
projects[0].onclick = function () {
// Open / close the project
projects[0].classList.toggle("opened");
console.log("Project 1 opened / closed");
};
projects[1].onclick = function () {
// Open / close the project
projects[1].classList.toggle("opened");
console.log("Project 2 opened / closed");
};
projects[2].onclick = function () {
// Open / close the project
projects[2].classList.toggle("opened");
console.log("Project 3 opened / closed");
};
projects[3].onclick = function () {
// Open / close the project
projects[3].classList.toggle("opened");
console.log("Project 4 opened / closed");
};
Project Name
Project Name 2
Project Name 3
Project Name 4
Looping through arrays
Other than storing multiple values in them, arrays come in very
handy when you want to loop through them and perform an action on
each value. To loop through an array, you use a
for
loop. The loop will run through all the values in the array, and
execute the code inside the loop for each value. The loop will
continue until it has gone through all the values in the array. You
can also use the
forEach()
method, which does the same thing, but in a more concise way. Here
is the same example as before, but using a loop:
// Select all the elements with the class "project"
var projects = document.querySelectorAll(".project");
// A function to toggle the opened class on a project
function forLoopToggleOpened(project) {
project.classList.toggle("opened");
}
// Loop through the array using a for loop
for (var i = 0; i < projects.length; i++) {
var project = projects[i];
project.onclick = function () {
// `this` refers to the element that was clicked
forLoopToggleOpened(this);
};
}
// Loop using the forEach method
projects.forEach(function (project) {
// Open each project when code is executed
project.classList.add("opened");
});
Project Name
Project Name 2
Project Name 3
Project Name 4