The if
statement in JavaScript is used to execute a block of code based on a specified condition. If the condition evaluates to true
, the code within the if
block will run.
JavaScript If Statement
1. Basic Syntax
The syntax for an if
statement is as follows:
if (condition) {
// code to be executed if condition is true
}
Here, condition
is an expression that evaluates to true
or false
.
2. Example of an If Statement
Here’s a simple example of using an if
statement:
const age = 18;
if (age >= 18) {
console.log('You are an adult.');
}
In this example, since the age
variable is 18, the message "You are an adult." will be logged to the console.
3. If-Else Statement
You can also use an else
clause to execute code when the condition is false
.
if (age >= 18) {
console.log('You are an adult.');
} else {
console.log('You are a minor.');
}
In this case, if age
is less than 18, "You are a minor." will be logged.
4. Else If Statement
You can chain multiple conditions using else if
:
if (age < 13) {
console.log('You are a child.');
} else if (age < 18) {
console.log('You are a teenager.');
} else {
console.log('You are an adult.');
}
This example checks for three different age ranges and logs the appropriate message.
5. Nested If Statements
You can also nest if
statements within each other:
const score = 85;
if (score >= 60) {
console.log('You passed!');
if (score >= 90) {
console.log('Excellent job!');
}
} else {
console.log('You failed.');
}
Here, if the score is 90 or above, it will log "Excellent job!" in addition to "You passed!".
6. Conclusion
The if
statement is a fundamental building block for conditional logic in JavaScript. By using if
, else
, and else if
statements, you can control the flow of your code based on different conditions.
Note: We aim to make learning easier by sharing top-quality tutorials, but please remember that tutorials may not be 100% accurate, as occasional mistakes can happen. Once you've mastered the language, we highly recommend consulting the official documentation to stay updated with the latest changes. If you spot any errors, please feel free to report them to help us improve.