Introduction
**
In JavaScript, you may need to choose one path out of multiple options while writing a program. For such scenarios, you must use conditional statements so programs can make correct decisions and take the right actions.
What are Conditional Statements?
**
Conditional statements are used to make decisions in a program. They let the program choose different actions depending on whether a condition is true or false.
**Why Use Conditional Statements?
To control the flow of a program
To make decisions based on user input or data..
JavaScript supports four types of if-else statements:
1.JavaScript if-statement
2.JavaScript if-else statement
3.JavaScript if-else-if ladder statement
4.JavaScript nested-if statement
JavaScript if-statement
The if statement evaluates a condition inside parentheses. If the condition is true, the block of code inside the curly braces {} runs. If it’s false, it skips that block
Syntax:
if(condition)
{
// Statements to execute if
// condition is true
}
JavaScript if-else statement
The if-else statement is another form of control statement that enables JavaScript to execute the code in a more controlled manner. The ifstatement tells the program to execute a block of code if the given condition is true, and if the condition is false, it won’t execute the statement.
However, what if we want another action if the condition is false? Hence, we use if-else in JS to execute the block of code.even the condition is false.
Syntax
if (condition) {
// statement to
// execute if condition is true
}
else {
// statement to
// execute if condition is false
}
JavaScript if-else-if ladder statement
The if-else-if statement in JavaScript, or if-else ladder, is an advanced if-else statement that allows JavaScript to make decisions based on several conditions. The statements are executed from top to bottom. When the condition controlling the if evaluates to be true, the statement related to that block is also executed, and the rest of the blocks are bypassed. If no condition is true, the final else statement is executed.
Syntax
if (condition)
statement;
else if (condition)
statement;
.
.
else
Statement;
Here, we use else-if in JavaScript to execute the code. If the condition is true, the body of if is executed, and the rest of the blocks are skipped. If the condition in the else-if statement is true, the given statement is executed. And if no condition is met, the code block in else is executed
JavaScript nested-if statement
In JavaScript, we use the nested if statements within if statements, placing one statement inside another. A nested if is another type of an if statement that is the target of another if or else.
Syntax
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse