If statements in JavaScript are a fundamental part of controlling the flow of a program. They allow you to execute code blocks based on certain conditions. If the condition evaluates to true, the code block within the if statement is executed. If the condition is false, the code block is skipped.
Syntax
The basic syntax of an if statement is:
if (condition) {
// code to be executed if condition is true
}
Example
let age = 18;
if (age >= 18) {
console.log("You are an adult.");
}
In this example, since age
is equal to 18, the condition age >= 18
evaluates to true, so the message "You are an adult." is printed to the console.
If-Else Statement
To execute a different block of code if the condition is false, you can use an if-else statement:
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
Example
let age = 16;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
In this case, since age
is 16, the condition age >= 18
is false, so the code block inside the else statement is executed, printing "You are a minor." to the console.
If-Else If-Else Statement
For multiple conditions, you can chain if statements using else if:
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition1 is false and condition2 is true
} else {
// code to be executed if both condition1 and condition2 are false
}
Example
let score = 85;
if (score >= 90) {
console.log("Grade A");
} else if (score >= 80) {
console.log("Grade B");
} else {
console.log("Grade C or below");
}
In this example, score
is 85, which does not meet the first condition (score >= 90
) but meets the second condition (score >= 80
). Therefore, "Grade B" is printed to the console.
Nested If Statements
You can also nest if statements within each other:
if (condition1) {
// code to be executed if condition1 is true
if (condition2) {
// code to be executed if condition1 and condition2 are true
}
}
Considerations
- The condition in an if statement is any expression that evaluates to true or false. JavaScript uses type coercion in boolean contexts, which means values like
0
,NaN
,""
(empty string),null
,undefined
, andfalse
are considered falsy, and everything else is truthy. - It's important to use strict equality (
===
) or inequality (!==
) operators when comparing values to avoid unexpected type coercion.