Conditional Statements in JavaScript

There are three conditional statements in JavaScript - if, if .. else, and switch.

1. if

The if statement evaluates an expression and, based on the results, determines which code, if any, executes within a program. More complex if statements can control which code executes based on multiple conditions. It can control how a program acts depending on whether a variable contains a certain value or a form field is filled in correctly.

The basic structure of an if statement is:

if (some condition) {
// do something here

The if statement examines the validity, or truthfulness, of a condition to determine whether the code within the conditional (inside the braces) is to be executed. The condition is a Boolean expression that, when evaluated to true, causes the if statement to execute the code in the conditional.

You can negate an expression in the condition to cause the code to run if the expression evaluates to false. For example,

if (! some condition) {
// do something here
}

In this case, the condition starts with the negation operator, which means that the condition would need to evaluate to false for the code inside the conditional to execute.

Compound Conditions

Often, you need to test for more than one condition within the same if statement. For example,

if ((inputNum < 51 ) || (inputNum > 99)) {
alert("That number, " + inputNum + ", is not between 50 and 100.");
}

The above statement the logical OR operator and reads, "If inputNum is less than 51 or inputNum is greater than 99, do this".

2. else if / else

Using else if and else, you can create multiple levels of conditions, each of which is tested in turn. The code within the first matching condition is executed. If nothing matches, the code inside the else condition, if present, is executed.

3. switch

The switch statement is an easy and efficient way to test a variable for several values and then execute code based on whichever case matches. Although you can accomplish the task by using if/else if statements, doing so can be cumbersome. The switch statement is more useful for this situation.

The switch has one or more case blocks and an optional default.

switch(x) {
case 'value1': // if (x === 'value1')
...
[break]

case 'value2': // if (x === 'value2')
...
[break]

default:
...
[break]
}

The value of x is checked for a strict equality to the value from the first case (value1), then to the second case (value2) and so on. If the equality is found, switch starts to execute the code starting from the corresponding case, until the nearest break (or until the end of switch). If no case is matched, then the default code is executed (if it exists).

If there is no break, then the execution continues with the next case without any checks.

The equality check is always strict. The values must be of the same type to match.

Star InactiveStar InactiveStar InactiveStar InactiveStar Inactive