The if
statement is a fundamental control structure in JavaScript that allows us to make decisions based on a condition. It is used to selectively execute a code block if the condition evaluates to true.
The basic syntax of an if
statement is as follows:
1if (condition) {
2 // code to execute if condition is true
3}
Let's look at an example to understand how the if
statement works:
1const age = 25;
2
3if (age >= 18) {
4 console.log('You are eligible to vote!');
5}
In this example, we have a variable age
with a value of 25. The if
statement checks if the age is greater than or equal to 18. If the condition is true, the code block inside the curly braces will be executed and the message 'You are eligible to vote!' will be logged to the console.
The if
statement can also be followed by an else
statement to handle the case when the condition is false:
1const num = 10;
2
3if (num % 2 === 0) {
4 console.log('The number is even');
5} else {
6 console.log('The number is odd');
7}
In this example, we check if the num
variable is divisible by 2. If the condition is true, the message 'The number is even' is logged to the console. Otherwise, the message 'The number is odd' is logged.
The if
statement can also be used with multiple else if
statements to handle multiple conditions:
1const grade = 85;
2
3if (grade >= 90) {
4 console.log('A');
5} else if (grade >= 80) {
6 console.log('B');
7} else if (grade >= 70) {
8 console.log('C');
9} else if (grade >= 60) {
10 console.log('D');
11} else {
12 console.log('F');
13}
In this example, we check the value of the grade
variable and log the corresponding letter grade based on the condition. If none of the conditions are true, the message 'F' is logged.
The if
statement is a powerful tool for making decisions in JavaScript and is essential for writing conditional code.