Javascript if Statement

Introduction

The if statement has the following syntax:

if (condition) 
   statement1 
else 
   statement2 

The condition can be any expression.

It doesn't even have to evaluate to an actual Boolean value.

Javascript automatically converts the result of the expression into a Boolean by calling the Boolean() function.

If the condition evaluates to true, statement1 is executed.

If the condition evaluates to false, statement2 is executed.

Each of the statements can be either a single line or a code block.

if (i > 25) 
   console.log("Greater than 25.");  // one-line statement 
else { 
   console.log("Less than or equal to 25.");  // block statement 
} 

We can chain if statements together:

if (condition1) 
   statement1 
else if (condition2) 
   statement2 
else 
   statement3 

Here's an example:

if (i > 25) { 
 console.log("Greater than 25."); 
} else if (i < 0) { 
 console.log("Less than 0."); 
} else { 
 console.log("Between 0 and 25, inclusive."); 
} 



PreviousNext

Related