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 block of code only if the condition (expression) is true, as follows:

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 block of code and the condition is true or another block of code just in case the condition is false (else), as follows:

var num = 0; 
if (num === 1) { 
  console.log('num is equal to 1'); 
} else { 
  console.log('num is not equal to 1, the value of num is ' + num); 
} 

The if...else statement can also be represented by a ternary operator. For ...

Get Learning JavaScript Data Structures and Algorithms - Third Edition 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.