- JavaScript if, else, and else if
- Conditional Statements
- The if Statement
- Syntax
- Example
- The else Statement
- Example
- The else if Statement
- Syntax
- Example
- More Examples
- if. else
- Синтаксис
- Описание
- Примеры
- Использование if. else
- Использование else if
- Присваивание в условном выражении
- Спецификации
- Совместимость браузеров
- Смотрите также
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
JavaScript if, else, and else if
Conditional statements are used to perform different actions based on different conditions.
Conditional Statements
Very 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:
- Use if to specify a block of code to be executed, if a specified condition is true
- Use else to specify a block of code to be executed, if the same condition is false
- Use else if to specify a new condition to test, if the first condition is false
- Use switch to specify many alternative blocks of code to be executed
The switch statement is described in the next chapter.
The if Statement
Use the if statement to specify a block of JavaScript code to be executed if a condition is true.
Syntax
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate a JavaScript error.
Example
Make a «Good day» greeting if the hour is less than 18:00:
The result of greeting will be:
The else Statement
Use the else statement to specify a block of code to be executed if the condition is false.
if (condition) // block of code to be executed if the condition is true
> else <
// block of code to be executed if the condition is false
>
Example
If the hour is less than 18, create a «Good day» greeting, otherwise «Good evening»:
The result of greeting will be:
The else if Statement
Use the else if statement to specify a new condition if the first condition is false.
Syntax
if (condition1) // block of code to be executed if condition1 is true
> else if (condition2) // block of code to be executed if the condition1 is false and condition2 is true
> else // block of code to be executed if the condition1 is false and condition2 is false
>
Example
If 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) <
greeting = «Good morning»;
> else if (time < 20) <
greeting = «Good day»;
> else <
greeting = «Good evening»;
>
The result of greeting will be:
More Examples
Random link
This example will write a link to either W3Schools or to the World Wildlife Foundation (WWF). By using a random number, there is a 50% chance for each of the links.
if. else
Инструкция if выполняет инструкцию, если указанное условие выполняется (истинно). Если условие не выполняется (ложно), то может быть выполнена другая инструкция.
Синтаксис
if (условие) инструкция1 [else инструкция2]
Выражение, которое является либо истинным, либо ложным.
Инструкция, выполняемая в случае, если значение «условиe» истинно ( true ). Может быть любой инструкцией в том числе и вложенным if . Для группировки нескольких инструкций используется блок ( <. >), Когда никакого действия не требуется, может использоваться пустая инструкция.
Инструкция, выполняемая в случае, если значение «условиe» ложно ( false ). Может быть любой инструкцией, в том числе и вложенным if . Инструкции тоже можно группировать в блок.
Описание
Несколько команд if . else могут быть вложены для создания условия else if . Обратите внимание, что в JavaScript нет ключевого слова elseif (в одно слово).
if (условие1) инструкция1 else if (условие2) инструкция2 else if (условие3) инструкция3 . else инструкция
Чтобы увидеть, как это работает, ниже представлен пример правильного вложения с отступами:
if (условие1) инструкция1 else if (условие2) инструкция2 else if (условие3) .
Чтобы выполнить несколько инструкций в условии, используйте блочный оператор (<. >) для группирования этих инструкций. В общем, хорошей практикой всегда является использование блочных операторов, особенно в коде, включающем вложенные операторы if :
Не путайте примитивные логические значения true и false с правдивостью или ложностью булева объекта. Любое значение, которое не undefined , null , 0 , NaN или пустая строка («»), и любой объект, включая объект Boolean, значение которого является ложным, считается правдивым при использовании в качестве условия. Например:
var b = new Boolean(false); if (b) // это условие истинно
Примеры
Использование if. else
if (cipher_char === from_char) result = result + to_char; x++; > else result = result + clear_char; >
Использование else if
Обратите внимание, что в JavaScript нет синтаксиса elseif . Однако вы можете записать его с пробелом между else и if :
if (x > 5) > else if (x > 50) > else >
Присваивание в условном выражении
Целесообразно не использовать простые присваивания в условном выражении, потому что при взгляде на код присваивание можно путать с равенством. Например, не используйте следующий код:
Если вам нужно использовать присваивание в условном выражении, обычной практикой является размещение дополнительных скобок вокруг присваивания. Например:
Спецификации
Совместимость браузеров
BCD tables only load in the browser
Смотрите также
Found a content problem with this page?
This page was last modified on 7 нояб. 2022 г. by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.