How to use if statement in Javascript

Description

The if statement has the following syntax:


if (condition) 
   statement1 
else 
   statement2

The condition can be any expression. Javascript converts the expression into a Boolean using Boolean() function.

If the condition evaluates to true, statement1 is executed; if the condition evaluates to false, statement2 is executed.

Example

In the following code the conditional expression compares the value myAge against a numeric value of 13:


var myAge = 12;
if(myAge <  13) { //w ww . ja  v a2s  .c  o  m
   console.log("under 13.");
} 

var i = 3;
if (i){
   console.log("true"); 
}else {
   console.log("false");
} 

The code above generates the following result.

if else ladder

You can also chain if statements together.


if (condition1) /*w ww  .  ja  v a2 s  .c  om*/
   statement1 
else if (condition2) 
   statement2 
else 
   statement3

Example 2

Here's an example:


var i = 50;
if (i > 25) {//from  w  ww  .  j  a  v a 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."); 
} 

The code above generates the following result.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions