JS Conditional Statement - If Else

JavaScript

Share

In this tutorial we will learn about JavaScript conditional statement If Else.

We use conditional statement to execute a piece of code if some condition is satisfied.

if statement

We use the if keyword to create an if statement.

Syntax:

if ( comparison ) {
	//some code goes here...
}

In the following example we have an if statement and the code inside it is executed if the condition is satisfied.

var x = 10;

console.log("x = " + x);

if ( x > 0 ) {
	console.log("x is greater than 0");
}

console.log("End of code");

In the above code we have created an if statement. We have a variable x set to 10. In the if statement we are checking if x > 0. This is true hence code inside the if block is executed.

Output:

x = 10
x is greater than 0
End of code

if/else statement

We use the if and else keywords to create an if/else statement.

Syntax:

if ( comparison ) {
	//if block code
} else {
	//else block code
}

In the following example we have an if statement and the code inside it is executed if the condition is satisfied. Otherwise, the else block is executed.

var x = 10;

console.log("x = " + x);

if ( x > 20 ) {
	console.log("x is greater than 20");
} else {
	console.log("x is less than 20");
}

console.log("End of code");

In the above code we have created an if/else statement. We have a variable x set to 10. In the if statement we are checking if x > 20. This is false hence code inside the else block is executed.

Output:

x = 10
x is less than 20
End of code

else if statement

We can combine the else and if keywords to create multiple if/else statement.

Syntax:

if ( comparison1 ) {
	//if block1 code
} else if ( comparison2 ) {
	//if block2 code
} else {
	//else block code
}

In the following example we have multiple if/else statement.

var x = 10;

console.log("x = " + x);

if ( x < 0 ) {
	console.log("x is less than 0");
} else if ( x == 0) {
	console.log("x is equal to 0");
} else {
	console.log("x is greater than 0");
}

console.log("End of code");

In the above code we have created an if/else statement. We have a variable x set to 10. In the if statement we are checking if x > 20. This is false hence code inside the else block is executed.

Output:

x = 10
x is greater than 0
End of code

Nesting if/else

We can have if/else statements inside another if/else statement.

Following is an example of a nested if/else statement.

var x = 10;
var y = 20;

if ( x > 0 ) {
	
	if ( y > x ) {
		console.log("y is greater than x");
	} else if ( y == x ) {
		console.log("y is equal to x");
	} else {
		console.log("y is less than x");
	}

} else {
	console.log("x is not greater than zero");
}

Output:

y is greater than x