Hướng dẫn conditional statement in javascript
Conditional statements are used to perform different actions based on different conditions. Show Conditional StatementsVery often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this. In JavaScript we have the following conditional statements:
The The if StatementUse the Syntax if
(condition) { Note that ExampleMake a "Good day" greeting if the hour is less than 18:00: if (hour < 18) { The result of greeting will be: Try it Yourself » The else StatementUse the if (condition) { ExampleIf the hour is less than 18, create a "Good day" greeting, otherwise "Good evening": if (hour < 18) { The result of greeting will be: Try it Yourself » The else if StatementUse the Syntax if (condition1) { ExampleIf time is less than 10:00, create a "Good morning" greeting, if not, but time is less than 20:00, create a "Good day" greeting, otherwise a "Good evening": if (time < 10) { The result of greeting will be: Try it Yourself » More ExamplesRandom link The condition An expression that is considered to be either truthy or falsy. statement1 Statement that is executed if condition is
truthy. Can be any statement, including further nested statement2 Statement that is executed if DescriptionMultiple
To see how this works, this is how it would look if the nesting were properly indented:
To execute multiple statements within a clause, use a block statement (
Not using blocks may lead to confusing behavior, especially if the code is hand-formatted. For example:
This code looks innocent — however, executing
In general, it is a good practice to always use block statements, especially in code involving nested
Do not confuse the primitive Boolean values
ExamplesUsing if...else
Using else ifNote that there is no
Using an assignment as a conditionYou should almost never have an
However, in the rare case you find
yourself wanting to do something like that, the Specifications
Browser compatibilityBCD tables only load in the browser See also |