I started studying Programming with JavaScript course by Meta. As I always like to take notes when learning a new topic, I thought it would be good to put my notes inside blog posts and share them. Hopefully, someone will find them useful.
Kindly note that this is not my first programming language, so I won't take detailed notes. I will take notes of the details that I may need to refresh only.
In this post, I included notes about:
- Comments in JavaScript
- The semi-colon in JavaScript
- Variables
- Data types
- Comparison Operators
- Logical Operators
- Conditionals and Loops
Comments in JavaScript
-
Single-line comments
// this is a comment!
-
Multi-line comments
/* this is a multi-line comment */
The semi-colon in JavaScript
Interestingly, the browser has a feature known as "Automatic Semi-colon Insertion" - meaning, it does a pretty good job of "filling in the blanks" in case there is a missing semi-colon where there should be one.
Effectively, what that means for developers is that most of the time, it makes no difference if a semi-colon is added or not, since the browser is likely to figure it out anyway.
That's why some developers say that you shouldn't bother with adding semi-colons at all.
However, other developers argue that it's better to use it wherever it's needed - for clarity.
The truth is that most of the time, you can think of adding semi-colons in JavaScript as optional - and somewhat of a stylistic preference.
Variables
To declare a variable
var petDog = 'Rex';
To update the value of a variable, you don't need to use the keyword var as the console is already aware of your variable:
petDog = 'Pepper';
Data types
Strings must be enclosed in either single or double quotations.
The boolean data type has two values of true and false (in lowercase).
Sometimes it's necessary to know when a variable does not contain a value. And JavaScript has two data types to express just that. First, there is the null data type which only has the value null and represents the absence of value. You also have the undefined data type which can only hold the value undefined and usually refers to a variable that has not yet been assigned a value.
The capabilities of JavaScript have evolved over time and version ES6 introduced two new primitive data types to help with more complex tasks. One is the BigInt data type which is like an extra-large box that can accommodate a much greater range of numbers than the number data type.
Finally, there is the symbol data type which can be used as a unique identifier. Think of it as having multiple boxes with the same label and using different serial numbers to avoid mixing them up.
Comparison Operators
There are two types of the equality operator similar to each other but behave in different ways:
-
The equality operator, ==
-
The strict equality operator, ===
The equality operator == compares the values on the right versus the value on the left. But it ignores the data type in this comparison. For example, the following comparison will result in true:
100 == "100" // True
While the strict equality operator === checks both the values and the data types on both sides. That means, for the same previous comparison, the result will be False; because even though the values are the same, the data types are different:
100 === "100" // False
Similarly, there are two types of the inequality operator:
- The inequality operator, !=
- The strict inequality operator !==
The inequality operator checks if two values are not the same, but it does not check against the difference in types.
5 != "5" // false
For the strict inequality operator to return false, the compared values have to have the same value and the same data type.
5 !== 5 // false
5 !== "5" // true
Combining strings and numbers using the + operator
Consider the following example:
1 + "2"
What will be the result of 1 + "2"?
Note that the value of 1 is of the number data type, and the value of "2" is of the string data type, so JavaScript will coerce the number 1 to a string of "1", and then concatenate it with the string of "2", so the result is a string of "12".
Logical Operators
Conditionals and Loops
if & else
if(light == "green") {
console.log("Drive")
} else if (light == "orange") {
console.log("Get ready")
} else if (light == "red") {
console.log("Dont' drive")
} else {
//this block will run if no condition matches
console.log("The car is not green, orange, or red");
}
switch statement
//converting the previous if-else example with switch-case
switch(light) {
case 'green':
console.log("Drive");
break;
case 'orange':
console.log("Get ready");
break;
case 'red':
console.log("Don't drive");
break;
default:
//this block will run if no condition matches
console.log('The light is not green, orange, or red');
break;
}
for loops
for (var i = 1; i <= 5; i++) {
console.log(i);
};
console.log('Counting completed!');
for (var i = 5; i > 0; i--) {
console.log(i);
};
console.log('Countdown finished!');
while loops
var i = 1;
while (i < 6) {
console.log(i);
i++;
};
console.log('Counting completed!');
var i = 5;
while (i > 0) {
console.log(i);
i = i - 1;
};
console.log('Counting completed!');
Nested loops
//nested loops - one inside another
for (var firstNum = 0; firstNum < 2; firstNum++) {
for (var secondNum = 0; secondNum < 10; secondNum++) {
console.log(firstNum + ", " + secondNum);
}
}
//nested loops - one inside another
for (var firstNum = 0; firstNum < 2; firstNum++) {
for (var secondNum = 0; secondNum < 10; secondNum++) {
console.log(firstNum + " times " + secondNum + " equals " + firstNum * secondNum);
}
}
Uses of loops
var cubes = 'ABCDEFG';
//styling console output using CSS with a %c format specifier
for (var i = 0; i < cubes.length; i++) {
var styles = "font-size: 40px; border-radius: 10px; border: 1px solid blue; background: pink; color: purple";
console.log("%c" + cubes[i], styles)
}
Running this simple code in the browser's console, the output in the console shows each letter on a separate line, styled like a letter cube for toddlers.
The code itself should be mostly familiar, except for the cubes.length and the cubes[i] syntax.
Without getting into too many details, here are both code snippets explained as simple as possible.
The cubes.length returns a number. Since cubes is a string of characters the cubes.length gives me the length of the string saved in the variable.
The second piece of code that's new here is the cubes[i] snippet.
This simply targets each individual letter in the loop, based on the current value of the i variable.
In other words, cubes[i], when i is equal to 0, is: A.
Then, cubes[i], when i is equal to 1, is: B.
This goes on for as many loops my for loop runs - and this is determined by the cubes.length value.
It's also very versatile, since, if I, for example, decided to change the length of the cubes string, I would not have to update the condition of i < cubes.length, because it gets automatically updated when I change the length of the cubes string.
Some additional examples
If I'm coding an email client, I will get some structured data about the emails to be displayed in the inbox, then I'll use a loop to actually display it in a nicely-formatted way.
If I'm coding an e-commerce site selling cars, I will get a source of nicely-structured data on each of the cars, then loop over that data to display it on the screen.
If I'm coding a calendar online, I'll loop over the data contained in each of the days to display a nicely-formatted calendar.
Exercise 1
In this exercise, you will create the code for a for loop, using the counter variable named i starting from 1.
To make the counter increment by 1 on each loop, you will use i++.
The exit condition for the for loop should match the output given below.
Inside the loop, write an if-else statement, which will check the following conditions:
-
First, it will check if the value of i is 1. If it is, your code will console log the string "Gold medal".
-
Next, I will check if the value of i is 2. If it is, your code will console log the string "Silver medal".
-
Then, your code will check if the value of i is 3. If it is, it will console log the string "Bronze medal".
-
For all the remaining values of i, your code will console log just the value of i.
Exercise 1 Solution
for (var i = 1; i <= 10; i++) {
if(i == 1) {
console.log("Gold medal")
} else if (i == 2) {
console.log("Silver medal")
} else if (i == 3) {
console.log("Bronze medal")
} else {
//this block will run if no condition matches
console.log(i)
}
}
Exercise 2
Use the completed code from the previous task, but convert the conditionals to a switch statement.
When you code the solution, the output in the console should remain exactly the same as in the previous question.
Note: You'll need three separate cases for the three medals, and a default case for all other values of the i variable.
Exercise 2 Solution
for (var i = 1; i <= 10; i++) {
switch(i) {
case 1:
console.log("Gold medal")
break
case 2:
console.log("Silver medal")
break
case 3:
console.log("Bronze medal")
break
default:
//this block will run if no condition matches
console.log(i)
}
}