If Statements in JavaScript
Key Concepts
If statements are fundamental control structures in JavaScript that allow you to execute code blocks based on certain conditions. The key concepts include:
- If Statement
- Comparison Operators
- Logical Operators
- Nested If Statements
- Else Clause
- Else If Clause
If Statement
The if statement executes a block of code if a specified condition evaluates to true. The basic syntax is:
if (condition) { // code to execute if condition is true }
Comparison Operators
Comparison operators are used to compare values and return a boolean result (true or false). Common comparison operators include:
- Equal to (==)
- Not equal to (!=)
- Strict equal to (===)
- Strict not equal to (!==)
- Greater than (>)
- Less than (<)
- Greater than or equal to (>=)
- Less than or equal to (<=)
Logical Operators
Logical operators combine multiple conditions. The primary logical operators are:
- Logical AND (&&)
- Logical OR (||)
- Logical NOT (!)
Nested If Statements
Nested if statements occur when an if statement is placed inside another if statement. This allows for more complex decision-making processes.
Else Clause
The else clause is used to specify a block of code to be executed if the condition in the if statement is false.
Else If Clause
The else if clause is used to specify additional conditions to be checked if the initial if condition is false.
Examples
Here are some examples to illustrate the concepts:
Example 1: Basic If Statement
let age = 18; if (age >= 18) { console.log("You are an adult."); }
Example 2: If-Else Statement
let temperature = 25; if (temperature > 30) { console.log("It's hot outside."); } else { console.log("It's not too hot."); }
Example 3: If-Else If-Else Statement
let score = 75; if (score >= 90) { console.log("Grade: A"); } else if (score >= 80) { console.log("Grade: B"); } else if (score >= 70) { console.log("Grade: C"); } else { console.log("Grade: D"); }
Example 4: Nested If Statements
let isLoggedIn = true; let hasPermission = true; if (isLoggedIn) { if (hasPermission) { console.log("Access granted."); } else { console.log("Access denied. No permission."); } } else { console.log("Access denied. Not logged in."); }
Example 5: Using Logical Operators
let isWeekend = true; let isHoliday = false; if (isWeekend || isHoliday) { console.log("Enjoy your day off!"); } else { console.log("Back to work."); }
Understanding if statements and their variations is crucial for controlling the flow of your JavaScript programs, enabling you to make decisions based on various conditions.