Flat Preloader Icon

JS Conditional Statement

If Statement
Use the if statement to specify a block of JavaScript code to be executed if a condition is true.
				
					if (condition) {
// block of code to be executed if the condition is true
}
				
			
Example
				
					let x = 10;

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

				
			
Else Statement
Use the else statement to specify a block of code to be executed if the condition is false.
				
					 if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}

				
			
Example
				
					let x = 10;

if (x > 5) {
    console.log("x is greater than 5");
} else {
    console.log("x is less than or equal to 5");
}

				
			
Else if Statement
Use the else if statement to specify a new condition if the first condition is false.
				
					 if (condition1) {
// block of code to be executed if the condition1 is true.
} else if (condition2) {
// block of code to be executed if the condition1 is false and 
condition 2 is true.
} else {
// block of code to be executed if the condition1 is false and 
condition 2 is False.
}

				
			
Example
				
					let x = 10;

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

				
			
Nested if
A nested if is an if statement that is the target of another if or else. Nested if statements means an if statement inside an if statement. Yes, JavaScript allows us to nest if statements within if statements. i.e., we can place an if statement inside another if statement.
				
					if (condition1) {
// block of code to be executed if the condition1 is true.
} if (condition2) {
// block of code to be executed if the condition 2 is true.
}
				
			
Example
				
					let num = 15;

if (num > 0) {
    console.log("Number is positive");
    if (num % 2 === 0) {
        console.log("Number is even");
    } else {
        console.log("Number is odd");
    }
} else if (num < 0) {
    console.log("Number is negative");
} else {
    console.log("Number is zero");
}

				
			

Share on: