Refugees Code
JavaScript fundamentals
JavaScript fundamentals
Building blocks
Before extending the functionality of our website with JavaScript and manipulate the content of our website, we have to go through the basics of programming. The most fundamental building blocks are:
- Variables
- Conditionals
- Loops
- Functions
Variables
JavaScript variables are containers for storing data values. The 3 containers that you need to keep in mind are: var, const & let ; and naming also plays an important role. This 📖 article What is a variable?, will give you a wide understanding of these concepts, and you will also find an introducction to Arrays [] that we will cover further in more detail.
In programming, we're always working with data. Data is information. It can be a username, the number of likes a post has, the text in an email, a video file, etc. Anything you can see on a web page is data. For now we're going to work with data we create ourselves, but later on we will be working with data across the web!
Our first tool to handle data will be variables. But what are they?
Imagine you're cooking and you want to use pepper. If you have all your spices mixed together it would be very hard to find the ones you want.
But if we have containers for each one we can write names on each one and we can know what's inside of it by just looking at the name.
Variables are like containers. They help us work keep everything organized and make sure that we have access to our data in a clean and easy way. In a variable we can store pretty much anything that the computer can understand, like text or number, as well as other more mysterious data that we will take a look at later.
To understand how to use them, first let's take a look at a some code:
console.log("Hello world!");If we run this code we will see something like this in our browser.
console.log will print whatever is in between the parenthesis - ( ) - to the console in our browser's developer tools.
What do you think this next code might do?
let movie = "Avengers 2";
console.log(movie);Going back to the spices analogy, imagine we have a container that we name movie and we put the text inside of it.
And imagine in the next line we take that container, grab the content and we put it on the screen.
In technical terms we would say: in the first line we declare a variable called movie and then assign the value Avengers 2 to it. Then in the next line, we log the content of our variable to the console.
To declare a variable means to "create" a variable, to assign means to "store" some data inside it, and the value is the data that the variable will hold. Let's break down how we do it:
let movie = "Avengers 2";- First we use the special word
letto tell the computer that we want to create a variable. - Then we give our variable a name. This name can be (almost) anything, but there are a few rules. You can check out the bullet points in this article.
- We use the "=" symbol. This will instruct the computer to store inside our variable whatever is on the right side of it.
📖 Try to create some variables with different texts and print all of them to the console.
We can also re-assign variables, like so:
let movie = "Avengers 2";
movie = "Titanic";
console.log(movie);📖 What do you think will happen? Try to run the code above.
let movie = "Avengers 2";
console.log(movie);
movie = "Titanic";
console.log(movie);📖 What about this one?
Variable types
There's two main type types of variables: let & const. The difference is that while with let we can reassign the variable to a new value, with const we can't. Once we declare the variable, we won't be able to change the value inside it. Maybe now it doesn't make much sense but sometimes we want to make sure that some values don't change.
const gravity = 9.8;📖 Try to declare a const and reassign it. What does the console say?
There is a third variable type: var, but it's an old way of writing JavaScript and we don't need to worry about it. If you come across some code using it, just know that it's almost the same as let.
Keywords, operators
In every programming language there's special words and symbols that the computer will understand as instructions.
const myVar = "Hello world!";We've seen that the words let & const will tell the computer that we want to create a variable.
These special words are called keywords and they're reserved for the language to use. If we try to use them for other purposes, like naming variables, we will get an error.
const let = 2; // SyntaxErrorWhen these words and symbols are instructions, they are called operators. For example, the symbol = will express that we want to assign the value on the right ('Hello world!') to the variable we're creating (myVar).
Data types
There is a set of different types of values JavaScript will understand:
- Number
- It can be an integer (a number without decimals. Ex: 34) or a float (a number which can have decimals. Ex: 34.245). It must be between -9007199254740991 and 9007199254740991.
- String
- Text. A sequence of characters. A character can be a letter ('a'), a sign ('?'), an emoji ('😃'), ...
- Boolean
trueorfalse. A simple yes or no.
- Undefined
- It represents a missing value. If you try to log a variable with no value assigned, it will log
undefined.
- It represents a missing value. If you try to log a variable with no value assigned, it will log
- Null
- Very similar to
undefined. It also represents a missing value but it has some very minor differences.
- Very similar to
There are two more advanced types. It's not necessary to get into them:
- BigInt
- If you need values bigger than 9007199254740991 or smaller than -9007199254740991, this is the data type for those.
- Symbol
- A unique value. Useful if it's necessary to give something a unique 'brand'.
JavaScript is a dynamic language, which means that we can assign different data types to the same variable. In a static language (like Java or C++ among others), this code would throw an error. But luckily for us, not in JavaScript.
let numberOfPets = 2;numberOfPets = "Hello world!";
Number
Any number between -9007199254740991 and 9007199254740991.
Arithmetic operators
We can make mathematical operations like sum and division. Here's a list of the available arithmetic operators.
console.log(2 + 2);console.log(4 / 2);One operator that might be unfamiliar is the modulo (%) operator. In programming it's not related to percentages. Instead it will give you the remainder of a division. A use case is to know if a number is even or odd. If you divide an even number by 2, the remainder will be 0, but the remainder of an odd number divided by 2 will be 1.
Note that a artihmetic operation is an expression, and it will be resolved before other operations. First, the computer evaluates 2 + 2, then stores the result in the variable.
const sum = 2 + 2;console.log(sum); // 4
We can also assign different values to variables and use the variable names instead of the values themselves
const firstValue = 2 + 2;const secondValue = 3;
console.log(firstValue - secondValue); // 1
// two different ways to do the same thing
const partial = 2 + 2;const total = partial - 3;
console.log(total); // 1Mathematical assignment operators
Imagine we're in a restaurant's kitchen and we have a variable named orders, which keeps track of the amount of orders the costumers have been placing.
let orders = 247;
console.log(orders);Now 39 new costumers have walked in the restaurant and placed orders. We need to update our variable. Let's try:
let orders = 247;let ordersUpdated = orders + 39;
console.log(ordersUpdated);This works, but we have to create a new variable for each update, and change the console.log to print the new variable. This is very messy and inefficient. Let's try again.
let orders = 247;
orders = orders + 3;
console.log(orders);This is looking better! It might seem counterintuitive how the second line works. The right side of an assignment operator (=) will resolve before assigning the new value to the variable. So in this case:
- In the first line we have our previous value.
- In the second line, the computer resolves the right hand side first
orders + 3(247 + 3). - When the right hand side is resolved, the total is re-assigned to our variable
orders. - The value is printed to the console.
While this works fine, there's an even easier way of doing it:
let orders = 247;
orders += 3;
console.log(orders);Here we're using a new assignment operator (+=). The result is exactly the same as the previous example but it's a slightly easier way of writing it. There's more assignment operators that you can check out here. Take a look at the mathematical ones and don't worry about the rest. You will probably never ever use them.
Increment/decrement operators
And sometimes you just want to count up (1, 2, 3, ...) or down (10, 9, 8, ...) a number. There's operators for that too.
let count = 0;
count++;
console.log(count); // 1
count--;
console.log(count); // 0The increment operator (++) will simply add 1 to the value in the varible. The decrement operator (--) will subtract 1.
Math operations
There's more complex operations we can perform with the object Math. It might seem a little bit like magic now, but when we get to functions it will make more sense.
There's operations like rounding decimals in a value,
const rounded = Math.round(12.67);
console.log(rounded); // 13Or getting a random number.
const random = Math.random();
console.log(random); // 0.3String
In order for the computer to understand that what we are writing is some plain text value and not part of our code instructions, we need to surround it using one of these three symbols:
- Apostrophes:
'Hello world!' - Quotation marks:
"Hello world!" - Backticks:
`Hello world!`
Concatenation
There's many cases in which we want to join to pieces of text. For example, here we have the general greeting, and the username and we need to combine them.
const username = "Zainab";const greeting = "Hello, ";
console.log(greeting + username); // Hello, ZainabWhen working with strings the "+" symbol is called concatenation operator, and will tell the computer to join two strings together, instead of summing to values like it did working with numbers. We can also use the assignment operator "+=" like so:
const greeting = "Hello, ";
gretting += "Zainab";
console.log(greeting); // Hello, ZainabInterpolation
There's another way of joining strings together using variables. The syntax looks a little funny but it's shorter when you want to use multiple variables. It looks like this:
const sentTo = "zainab.rf@outlook.com";const date = "February 6th, 2025";const time = "10:45 pm";
const fullString = `Email sent to ${sentTo} on ${date} at ${time}.`;
console.log(fullString); // Email sent to zainab.rf@outlook.com on February 6th, 2025 at 10:45 pm.String methods
Strings have tools called methods (which we will get to explain more in depth in the "Objects" chapter) to make our life a little easier when dealing with them. Let's start with a basic one:
Length
With this method we can automatically get the number of characters in the given string. All we need to do is write a dot after our string (.) and type length. Notice that it will count every character in the string, including blank spaces and symbols.
const paragraph = "I really don't want to count the characters one by one!";
const numberOfCharacters = paragraph.length;
console.log(numberOfCharacters); // 55Includes
This method will check if a string contains a certain substring, that is a smaller string inside of it. Notice how it lowercase and uppercase letters count as different characters. This method gives us one of two values: true or false. These values are called boolean and will be very useful for the "Conditionals" section comming up.
const paragraph = "I wonder if it contains the word PANDA!";
const uppercase = paragraph.includes("PANDA");const lowercase = paragraph.includes("panda");
console.log(lowercase); // trueconsole.log(uppercase); // falseThere's a lot more methods. Some will look very scary until we take a look at "Arrays". Here's a list of some common ones and a little explanation for each. And here we have all of the available ones.
typeof operator
What if we have a value and we want to check what type it is? We have a handy tool for that. We will place the typeof operator before our variable and it will give us a string with the name of the type
const pet = "cat";const amount = 2;const otherAmount = "2";
console.log(typeof pet); // stringconsole.log(typeof amount); // numberconsole.log(typeof otherAmount); // stringSee what happened with our variable otherAmount? When we place one character or more (like letters, numbers, symbols, ...) inside apostrophes (''), quotes ("") or backticks (``), we are telling the computer that we want it to take it as text.
Exercises on FreeCodeCamp
💡 Well done! now we will make a good use of all this learning and have fun achieving the following exercises at FreeCodeCamp. They might seem a lot, but we think it's important that you start familiarizing with all these new concepts. All of them are really important and will be of use on a daily basis.
- Basic JS Exercises
- Declare Javascript variables
- Initializing variables with the assignment operator
- Understanding case sensitivity in variables
- Finding a remainder in Javascript
- Compound assignment with augmented addition
- Concatenating strings with Plus Operator
- Constructing strings with variables
- Use bracket notation to find the first character in a string
Comments in JavaScript
Follow the instructions in this 🖥 tutorial, and you'll learn how to write JavaScript comments and be able to leave notes in your JavaScript code.
Even though it's not strictly required, it's very useful to start learning shortcuts for VSCode. A shortcut is a combination of keys that perform a specific action. For example, to make a single line comment, place the cursor in a line with text and then press
command+/if you're on a Mac computer, orcontrol+/if you're on a PC computer. And for a multiline comment, select a piece of text by clicking and dragging your mouse, then pressalt+shift+a. 📖 Try these two types of comments by writing them and by using shortcuts.
Conditionals
Conditional statements allow us to represent decision making in JavaScript, from the choice that must be made (e.g. "one cookie or two"), to the resulting outcome of those choices. The most common type of conditional statement is the if...else and the operators to keep in mind are:
=== means equal
!== means not equal
< or > test if one value is less than or greater than another.
<= or >= test if one value is less than or or equal to, greater than or equal to.
&& means AND
|| means OR
Here you have a step by step explanation of the different type of conditionals in slides. You can also check out this tutorial in the JavaScript's official documentation page.
- Conditional statements exercises
- Comparison with the Equality Operator
- Comparison with the Strict Equality Operator
- Practice comparing different values
- Use Conditional Logic with If Statements
- Logical Order in If Else Statements
- Chaining If Else Statements
Arrays
Until now we've only dealt with single values, like a number or a string. But often we want to have collections of information. Imagine our restaurant kitchen. We need a list of orders that customers make for the kitchen to make them. Or a list of items in our menu. That's where arrays come in handy.
An array is a list of values (strings, numbers, booleans, etc.) that we can have in order, one after the other. We can also save the list itself to a variable in order to do more advanced things, like do an operation on every item of the list, reverse it, split it, and many more.
const menuItems = ["beef_kebab", "roast_chicken", "rice", "salad"];Here is an introduction to the concept of arrays. You can use the arrow keys to navigate through the slides.
And here we have info on arrays properties and methods. This is how we work with arrays.
Exercises on FreeCodeCamp
- Array Exercises
- Store multiple values in one variable using javascript arrays
- Nest one array within another array
- Access Multi-Dimensional Arrays With Indexes
- Manipulate Arrays With push()
- Manipulate Arrays With pop()
- Manipulate Arrays With shift()
- Manipulate Arrays With unshift()
Loops and iteration
In programming, Loops are used to repeat a block of code many times. For example, if you want to run some code 5 times, loops allow us to write it once, but make the computer run it 5 times. Or if you have an array and want to perform an action for every item in the array.
Here we have an explanation of how loops work.
There's various types of loops. The one you'll be using most (and the easier to understand) is for ... of. It's also useful to understand and be able to write the basic for (the scary looking one in the slides) and the while loops, as well as the break and continue keywords. You can read about them in this 📖 article Loops and iteration
There's a couple more loops that we can throw in, even though will make more sense further on in the course.
- The
for ... inloop when we get to the "Objects" section of the course. - The forEach array method. It will loop through the array's items, similarly to a
for ... of, running an anonymous function for each item, which will see in the "Functions" section.
Exercises on FreeCodeCamp
💡 🌟 Until here, we have covered the most important tools in order to start with loops 🤘 Let's keep rocking this learning path with some exercises from FreeCodeCamp.
- Loops Exercises
- Iterate with JavaScript While Loops
- Iterate with JavaScript For Loops
- Iterate Odd Numbers With a For Loop
- Count Backwards With a For Loop
- Nesting For Loops
- Iterate with JavaScript Do...While Loops
- Iterate Through an Array with a For Loop
Functions
A function is a code snippet that can be called by other code or by itself, or a variable that refers to the function. In other words, function definition include the orders and function calls state when to execute those orders. In this 📖 article Where do I find functions?, you'll explore fundamental concepts behind functions such as basic syntax, how to invoke and define them, scope, and parameters.
Exercises on FreeCodeCamp
💡 So far we have learnt about variables, conditionals, arrays and functions. It seems we are ready to start writing our own functions with these exercises from FreeCodeCamp
- Function Exercises
- Write Reusable JavaScript with Functions
- Passing Values to Functions with Arguments
- Return a Value from a Function with Return
Exercises for further practice
💡 Next, you will find a series of exercises that summarize what you've learnt throughout this lesson and exercises at FreeCodeCamp. Try to do them on your own, we haven't introduced anything new and all of them just go through what you've seen until this section. Remember you can always ask any staff member on Slack. Give it a try!
- Exercise 1 - The Lifetime Supply Calculator
How many potatoes will a person eat until the end of his life? Discover yourself!
- Store the persons current age into a variable.
- Store an estimated maximum age into a variable.
- Store an estimated amount per week (as a number).
- Calculate how many weeks will happen until the end of this person life.
- Calculate how many potatoes would eat total for the rest of his life.
- Output the result to the screen by console like so: "NAME has NN years and will eat NN potatoes until age of X".
- Exercise 2 - True or false
Using prompt, variables and conditionals, ask questions to the users and display the result on the console.
- Ask: "Tomatoes are fruits, not vegetables: true or false". If that answer is "true" you show "correct", otherwise show "incorrect".
- Ask: "You should drink 8 glasses of water: true or false". If that answer is "false" you show "correct", otherwise show "incorrect".
- Ask: "Fishes have only three seconds of memory: true or false". If that answer is "false" you show "correct", otherwise show "incorrect".
- Ask: "The Great Wall of China is the only man made structure visible from space The Great Wall of China: true or false". If that answer is "true" you show "correct", otherwise show "incorrect".
Have fun! Create more true or false questions.
Bonus points
- Create a variable
pointsand initialize it to zero. - If the answer is correct, add 10 points to the
pointsvariable. - If the answer is incorrect, remove 5 points to the
pointsvariable. - Display how many points the user has on the console.
- Exercise 3 - A dinner
Imagine you are a famous singer in a band and you want to invite other musicians to a dinner.
Write an array of every musician and its band in a format musician:band and using only one console log, display the list of assistants in the console.
Events and the DOM
DOM API
DOM is the shortcut for: The Document Object Model. And what does this means? Well in short "is the data representation of the objects that comprise the structure and content of a document on the web".
Ok, and what does this has to do with JavaScript? Let's read this 📖 article What is the DOM? to have a better understanding and how this two connect and what can be achieved.
Events listeners
Now we will have a look at the DOM event Model. First have a look at this diagram that explains the three phases of event flow through the DOM in the DOM Level 3 Events draft.
There are 3 ways to register event handlers for a DOM element, but we will only learn about the the method used in modern web pages:
- 🥇 EventTarget.addEventListener(): Read in detail 📖 here
- HTML attribute: This method should be avoided! It inflates the markup, and makes it less readable. Concerns of content/structure and behavior are not well-separated, making a bug harder to find.
- DOM element properties: The problem with this method is that only one handler can be set per element and per event.
Still curious about the difference between the 3 methods? 📖 Read this examples
Event API
The Event interface represents an event which takes place in the DOM. Event handlers may be attached to DOM elements: click on a button, the document, the Window...etc.
When an event occurs as we have seen before, a new event object is created through the event listeners.
Let's have a better look at this concept 📖 here and learn about the Interfaces based on Event
Add Event Listener
addEventListener() sets up a function that will be called whenever the specified event is delivered to the target. Ok, let's learn about the Syntax behind this, read the 📖 article about EventTarget.addEventListener()
Exercises on FreeCodeCamp
💡Ok, now let's practice these new tools with these exercises at FreeCodeCamp.
- Use the JavaScript Console to Check the Value of a Variable
- Catch Misspelled Variable and Function Names
- Catch Unclosed Parentheses, Brackets, Braces and Quotes
- Catch Arguments Passed in the Wrong Order When Calling a Function
- Catch Off By One Errors When Using Indexing
- Prevent Infinite Loops with a Valid Terminal Condition