Condition

If else

JavaScript

 

If

ECMAScript 5
var status = 0;

if (status === 0) {
    console.log("Ready"); 
}

The code block {} will run if the condition specified is met.

Comparison Expressions and operators can be combined to form new condition expressions:

var status=0, isDeviceOn=true;

if (isDeviceOn && (status === 0 || status === 1)) {
  console.log('Not done yet');
}

This will print Ready on Console.

 

If Else

ECMAScript 5
var status = 1;

if (status === 0) {
    console.log("Ready"); 
} else {
    console.log("Running or Done");
}

By using else, you can specify a portion of code to be run, in case if expression evaluates to false.

This will print Running or Done on Console.

 

Complex If

ECMAScript 5
var status = 2;

if (status === 0) {
    console.log("Ready"); 
} else if (status === 1){
    console.log("Running");
} else {
    console.log("Done"); 
}

You can have as many else if as you want.

This will print Done on Console.

 

Nested If

ECMAScript 5
var status = 2;

if (status > 0) {
    if (status === 1){
        console.log("Running");
    } else {
        console.log("Done"); 
    }
} else {
    console.log("Ready");  
}

You can nest if statements to control the logic of your algorithms.

This will print Done on Console.

 

Single If Statement

ECMAScript 5
var status = 1;

if (status === 0)
    console.log("Ready"); 
else
    console.log("Running or Done");

If you only have one statement in your if-else blocks, you can drop the curly braces { }.

This will print Running or Done on Console.