The if statement is used to execute a block of code only when a specific condition is true. It allows JavaScript programs to make simple decisions.
Whenever you want your program to do something only in a certain situation, you use the if statement. This makes your program smart and responsive instead of running the same code every time.
When to Use the if Statement
- When you want code to run only if a condition is true
- When checking user input
- When validating forms
- When controlling access to features
- When making simple decisions in programs
The if statement is the foundation of all conditional logic.
In this example, JavaScript checks whether the value of age is greater than or equal to 18. If the condition is true, the message is displayed.
If the condition is false, nothing happens because there is no else block.
Here, the program checks if the user is logged in. If the condition is true, it shows a welcome message.
This type of logic is commonly used in real applications like websites and dashboards.
This example shows how the if statement can be used to check different conditions, such as whether a number is positive.
Mastering the if statement helps students build logic for more complex conditions like if…else, else if ladders, and nested conditions.