Javascript - Statement if Statement

Introduction

The if statement has the following syntax:

if (condition)
   statement1
else
   statement2

The condition can be any expression and it doesn't have to be an actual Boolean value.

ECMAScript converts the expression to 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 block statement. Consider this example:

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

It's considered best coding practice to always use block statements, even for one line of code.

You can chain if statements together like so:

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

Here's an example:

Demo

var i = 34;
if (i > 25) {/*from www.  j a va  2  s.  c o m*/
    console.log("Greater than 25.");
} else if (i < 0) {
    console.log("Less than 0.");
} else {
    console.log("Between 0 and 25, inclusive.");
}

Result

Exercise