The if…else statement allows a program to choose between two different actions. If the condition is true, one block of code runs. If the condition is false, a different block of code runs.
This makes programs more flexible because they can handle both success and failure situations, such as login success or login failure, pass or fail results, and access granted or denied.
When to Use if…else Statement
- When you need two possible outcomes
- When checking pass or fail conditions
- When validating user input
- When deciding between success and error messages
- When handling yes/no decisions in programs
The if…else statement is a key tool for building decision-making logic.
In this example, JavaScript checks whether the marks are greater than or equal to 40. If the condition is true, it shows a success message. Otherwise, it shows a failure message.
This demonstrates how if…else handles two different outcomes.
Here, JavaScript checks if the password is correct. Depending on the result, it shows the appropriate message.
This logic is commonly used in login systems and security checks.
This example shows how if…else can be used to make simple decisions such as checking whether a number is even or odd.
By learning if…else statements, students build the foundation for more advanced decision-making structures like else if ladders and nested conditions.