If-Else Conditionals
The "if" statement in JavaScript is used to execute a block of code if a certain condition is met. The "else" clause is used to execute a block of code if the condition is not met.
Basic syntax
Here is the basic syntax for an "if" statement:
if (condition) {
// code to be executed if the condition is true
}Here is the syntax for an "if" statement with an "else" clause:
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}The condition is a boolean expression that evaluates to either true or false. If the condition is true, the code in the "if" block is executed. If the condition is false, the code in the "else" block is executed (if present).
Examples
Here are some examples of using "if" and "else" statements in JavaScript:
let x = 10;
if (x > 5) {
console.log("x is greater than 5");
} else {
console.log("x is not greater than 5");
}In this example, the condition x > 5 evaluates to true, so the code in the "if" block is executed, and the output is:
x is greater than 5Here is another example:
let y = 3;
if (y % 2 === 0) {
console.log("y is even");
} else {
console.log("y is odd");
}In this example, the condition y % 2 === 0 evaluates to false, so the code in the "else" block is executed, and the output is:
y is oddConclusion
- The "
if" statement in JavaScript is used to execute a block of code if a certain condition is met. - The "
else" clause is used to execute a block of code if the condition is not met. - The condition is a boolean expression that evaluates to either
trueorfalse. - The "
if" statement can be followed by an "else" clause to handle the case when the condition is false.
How is this guide?
Sign in to share your feedback
Help us improve by sharing your thoughts on this guide.
Last updated on
var vs let vs const
In JavaScript, there are three ways to declare variables:- var, let, and const. Understanding the differences between these three methods is important for writing clean and maintainable code.
If-Else Ladder
The "if-else" ladder is a series of "if" and "else" statements that are used to test multiple conditions in sequence.