Control structures

JavaScript has a similar set of control structures as the C and Java languages. Conditional statements are supported by if…else and switch. Loops are supported by while, do…while, and for constructs.

Conditional statements

The first conditional statement we will take a look at is the if…else construct. There are a few ways we can use the if…else construct.

We can use the if statement if we want to execute a script only if the condition is true:

var num = 1;
if (num === 1) {
    console.log("num is equal to 1");
} 

We can use the if…else statement if we want to execute a script if the condition is true or another script just in case the condition is false (else):

var num = 0; if (num === 1) { console.log("num is equal to 1"); } else { ...

Get Learning JavaScript Data Structures and Algorithms now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.