JavaScript supports control flow statements similar to other programming languages. These statements allow you to control the flow of your program’s execution based on conditions.
JavaScript has an if statement similar to languages like Java and C++, except that the condition of an if statement can be anything that could be coerced to a boolean value (see the previous section on Boolean-ish values)
The statements inside an if block can contain other control structures, including other if statements (nested if statements).
An if condition can be expanded with an else block
If you have only one statement, the braces around that statement are optional. However, consider it good practice always to include braces.
You can chain several if statements:
The if
-else
-if
ladder exits at the first success. If the conditions overlap, the first criteria occurring in the flow of execution is executed.
Consider the following expression that uses the ternary operator ?
:
which is the same as
When needing to make a lot of comparisons for a single value, instead of using many if
-else
-if
statements, you can use the switch
statement:
default
case in a switch
statement is like the last else
in an ifelseif
chain. It will be reached if none of the previously tested conditions are true
.break
statement is needed to break out of the switch
statement. If you omit break
, switch
will run all the following cases until it encounters break
or exits. This behavior can be useful for grouping cases.Keep in mind that JavaScript uses strict equality for switch statements.