The if statement in Javascript

By: Syed Fazal Emailed: 1792 times Printed: 2623 times    

One of the most frequently used statements in JavaScript (and indeed, in many languages), is the if statement. 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 converts it to a Boolean for you. 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 (a group of code lines enclosed within braces). For example:

if (i > 25)
   alert(“Greater than 25.”); //one-line statement
else {
  alert(“Less than or equal to 25.”); //block statement
}

You can also chain if statements together like so:

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

Example:

if (i > 25) {

  alert(“Greater than 25.”)

} else if (i < 0) {

  alert(“Less than 0.”);

} else {

  alert(“Between 0 and 25, inclusive.”);

}

Tip: It’s considered best coding practice to always use block statements, even if only one line of code is to be executed. Doing so can avoid confusion about what should be executed for each condition.

Most Viewed Articles (in Javascript )

Latest Articles (in Javascript)

Comment on this tutorial