Conditional Statements in JavaScript
By Engr. Nabeel Yousaf
Conditional statements are used in programming to make decisions based on certain conditions. In JavaScript, there are several conditional statements that are commonly used including IF, Else, Else if, Switch, and the Ternary Operator.
IF Statement
The IF statement is used to execute a block of code if a specified condition is true. It follows the syntax:
if (condition) { // code to be executed if the condition is true }
Else Statement
The Else statement is used in conjunction with the IF statement to execute a block of code if the condition in the IF statement is false. It follows the syntax:
if (condition) { // code to be executed if the condition is true } else { // code to be executed if the condition is false }
Else if Statement
The Else if statement is used to specify a new condition to test if the previous conditions were false. It follows the syntax:
if (condition1) { // code to be executed if condition1 is true } else if (condition2) { // code to be executed if condition2 is true } else { // code to be executed if all conditions are false }
Switch Statement
The Switch statement is used to select one of many code blocks to be executed. It is often used as an alternative to multiple Else if statements. It follows the syntax:
switch (expression) { case value1: // code to be executed if expression matches value1 break; case value2: // code to be executed if expression matches value2 break; default: // code to be executed if expression does not match any value break; }
Ternary Operator
The Ternary Operator is a shortcut for the IF-Else statement. It follows the syntax:
(condition) ? value1 : value2;
If the condition is true, value1 is returned, otherwise, value2 is returned.