JavaScript – if…else Statement
While writing a program, there may be a situation when you need to adopt one out of a given set of paths. In such cases, you need to use conditional statements that allow your program to make correct decisions and perform right actions.
JavaScript supports conditional statements which are used to perform different actions based on different conditions. Here we will explain the if.else statement.
JavaScript If-else
The JavaScript if-else statement is used to execute the code whether condition is true or false. There are three forms of if statement in JavaScript.
- If Statement
- If else statement
- if else if statement
if statement
The if statement is the fundamental control statement that allows JavaScript to make decisions and execute statements conditionally.
Syntax
The syntax for a basic if statement is as follows −if (expression) { Statement(s) to be executed if expression is true }
Here a JavaScript expression is evaluated. If the resulting value is true, the given statement(s) are executed. If the expression is false, then no statement would be not executed. Most of the times, you will use comparison operators while making decisions.
Description
The if/else statement executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed.
The if/else statement is a part of JavaScript’s “Conditional” Statements, which are used to perform different actions based on different conditions.
In JavaScript we have the following conditional statements:
- Use if to specify a block of code to be executed, if a specified condition is true
- Use else to specify a block of code to be executed, if the same condition is false
- Use else if to specify a new condition to test, if the first condition is false
- Use switch to select one of many blocks of code to be executed
Add a Comment