Loops and Conditions

Now that we have understood the basic datatypes and operations of JavaScript, we can start learning about other constructs. This section will cover loops and conditions.

To clear the code in the console, type and enter clear(); or hit ctrl + L. This will still keep any variables you declared earlier.

To write multiple lines without executing them one at a time, hit ctrl + enter (or cmd + return for Mac) after every line instead of just enter. This will be useful for the this and the next few sections.

Conditionals

Conditionals are a set of statements that execute different blocks of code based on the evaluation of one or more boolean expressions. In simpler words, if something is true then one thing happens otherwise something else happens.

The syntax for conditional statements in JavaScript is as follows:

if (booleanExpression) {
    // do thing 1
} else if (otherBooleanExpression) {
    // do thing 2
} else {
    // do something else
}

Example:

let num = prompt("Enter a number"); // recall that this allows the user to input a value
if (num === null) { // prompt() returns null if the user gives no input
    alert("You did not enter a number");
} else if (num % 2 === 0) {
    alert("The number you entered was even");
} else {
    alert("The number you entered was odd");
}

Ternary operation

This is an operation that operates on 3 operands, specifically to allow the evaluation of a conditional statement in a single line. Like any other operation, ternary conditions can be nested. The syntax is as follows:

predicate ? returnIfTrue : returnIfFalse;

Example:

// assume num is guaranteed to be a number
num % 2 === 0 ? "Even" : "Odd"; // if num is even then "Even" is returned, else "Odd" is returned

Loops

A loop is a block of code that gets executed repeatedly until an end condition is satisfied. There are two types of loops in JavaScript, the for loop and the while loop. The syntax for each is as follows:

for (counter; limit; step) {
    // do something
}

while (condition) {
    // do something
}

An example of a for loop is as follows:

for (let i = 0; i < 11; i++) {
    console.log(i);
}

The loop above will print out numbers from 0 to 10 one by one. As you can see, first the counter is declared (let i = 0), then the limit is defined (loop keeps executing as long as i < 11), and then the step is defined (i is incremented by 1 each time; i++). The eventual output will look like this:

An while loop that does the same thing as the for loop above would be as below:

let i = 0;
while (i < 11) {
    console.log(i);
    i++;
}

Note that here, the counter variable declaration needs to be done outside the loop, and the step is defined inside the loop. This is because the while loop only has a boolean expression in its keyword call. Omitting to declare the counter variable will lead to a ReferenceError: i is not defined. On the other hand, omitting the step will cause an infinite loop, since the value of i will never change and is always less than 11.

In a for loop, the step can be of any size and can involve valid operation:

for (let k = 1024; k > 1; k /= 2) {
    console.log(k);
}

The above code prints out numbers backwards from 1024, each time dividing k by 2, as long as k is greater than 1.

The counter variable can also be of any type, and you can declare multiple counter variables:

for (let i = 0, j = 15; i < 5; i++, j -= 3) {
    console.log(i, j); // prints the values of i and j separated by a space
}

Here i increases by 1 each time from 0 to 4 (stopping at 5) while j decreases by 3 each time starting from 15 until the loop ends.

A loop involving strings:

let str = "eowjpfi45ofr;kl143";
let i = 0;
while (i < str.length) {
    console.log(str[i]);
    i += 2;
}

This loop prints every 3rd character of str, starting from the 1st one. The same result can be achieved with a for loop:

for (let i = 0; i < str.length; i += 2) {
    console.log(str[i]);
}

Similar results can be achieved with an array.

Next steps

In the next section, we'll look at functions, their types, and how to declare and use them.

Last updated