Условные операторы языка javascript

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.

Читайте также:  Html body font sans serif

Источник

Условное ветвление: if, ‘?’

Иногда нам нужно выполнить различные действия в зависимости от условий.

Для этого мы можем использовать инструкцию if и условный оператор ? , который также называют оператором «вопросительный знак».

Инструкция «if»

Инструкция if(. ) вычисляет условие в скобках и, если результат true , то выполняет блок кода.

let year = prompt('В каком году была опубликована спецификация ECMAScript-2015?', ''); if (year == 2015) alert( 'Вы правы!' );

В примере выше, условие – это простая проверка на равенство ( year == 2015 ), но оно может быть и гораздо более сложным.

Если мы хотим выполнить более одной инструкции, то нужно заключить блок кода в фигурные скобки:

Мы рекомендуем использовать фигурные скобки <> всегда, когда вы используете инструкцию if , даже если выполняется только одна команда. Это улучшает читаемость кода.

Преобразование к логическому типу

Инструкция if (…) вычисляет выражение в скобках и преобразует результат к логическому типу.

Давайте вспомним правила преобразования типов из главы Преобразование типов:

  • Число 0 , пустая строка «» , null , undefined и NaN становятся false . Из-за этого их называют «ложными» («falsy») значениями.
  • Остальные значения становятся true , поэтому их называют «правдивыми» («truthy»).

Таким образом, код при таком условии никогда не выполнится:

…а при таком – выполнится всегда:

Мы также можем передать заранее вычисленное в переменной логическое значение в if , например так:

let condition = (year == 2015); // преобразуется к true или false if (condition)

Блок «else»

Инструкция if может содержать необязательный блок «else» («иначе»). Он выполняется, когда условие ложно.

let year = prompt('В каком году была опубликована спецификация ECMAScript-2015?', ''); if (year == 2015) < alert( 'Да вы знаток!' ); >else < alert( 'А вот и неправильно!' ); // любое значение, кроме 2015 >

Несколько условий: «else if»

Иногда нужно проверить несколько вариантов условия. Для этого используется блок else if .

let year = prompt('В каком году была опубликована спецификация ECMAScript-2015?', ''); if (year < 2015) < alert( 'Это слишком рано. ' ); >else if (year > 2015) < alert( 'Это поздновато' ); >else

В приведённом выше коде JavaScript сначала проверит year < 2015 . Если это неверно, он переходит к следующему условию year >2015 . Если оно тоже ложно, тогда сработает последний alert .

Блоков else if может быть и больше. Присутствие блока else не является обязательным.

Условный оператор „?“

Иногда нам нужно определить переменную в зависимости от условия.

let accessAllowed; let age = prompt('Сколько вам лет?', ''); if (age > 18) < accessAllowed = true; >else < accessAllowed = false; >alert(accessAllowed);

Так называемый «условный» оператор «вопросительный знак» позволяет нам сделать это более коротким и простым способом.

Оператор представлен знаком вопроса ? . Его также называют «тернарный», так как этот оператор, единственный в своём роде, имеет три аргумента.

let result = условие ? значение1 : значение2;

Сначала вычисляется условие : если оно истинно, тогда возвращается значение1 , в противном случае – значение2 .

let accessAllowed = (age > 18) ? true : false;

Технически, мы можем опустить круглые скобки вокруг age > 18 . Оператор вопросительного знака имеет низкий приоритет, поэтому он выполняется после сравнения > .

Читайте также:  Python print with parentheses

Этот пример будет делать то же самое, что и предыдущий:

// оператор сравнения "age > 18" выполняется первым в любом случае // (нет необходимости заключать его в скобки) let accessAllowed = age > 18 ? true : false;

Но скобки делают код более простым для восприятия, поэтому мы рекомендуем их использовать.

В примере выше вы можете избежать использования оператора вопросительного знака ? , т.к. сравнение само по себе уже возвращает true/false :

// то же самое let accessAllowed = age > 18;

Несколько операторов „?“

Последовательность операторов вопросительного знака ? позволяет вернуть значение, которое зависит от более чем одного условия.

let age = prompt('Возраст?', 18); let message = (age < 3) ? 'Здравствуй, малыш!' : (age < 18) ? 'Привет!' : (age < 100) ? 'Здравствуйте!' : 'Какой необычный возраст!'; alert( message );

Поначалу может быть сложно понять, что происходит. Но при ближайшем рассмотрении мы видим, что это обычная последовательная проверка:

Вот как это выглядит при использовании if..else :

if (age < 3) < message = 'Здравствуй, малыш!'; >else if (age < 18) < message = 'Привет!'; >else if (age < 100) < message = 'Здравствуйте!'; >else

Нетрадиционное использование „?“

Иногда оператор «вопросительный знак» ? используется в качестве замены if :

let company = prompt('Какая компания создала JavaScript?', ''); (company == 'Netscape') ? alert('Верно!') : alert('Неправильно.');

В зависимости от условия company == 'Netscape' , будет выполнена либо первая, либо вторая часть после ? .

Здесь мы не присваиваем результат переменной. Вместо этого мы выполняем различный код в зависимости от условия.

Не рекомендуется использовать оператор вопросительного знака таким образом.

Несмотря на то, что такая запись короче, чем эквивалентная инструкция if , она хуже читается.

Вот, для сравнения, тот же код, использующий if :

let company = prompt('Какая компания создала JavaScript?', ''); if (company == 'Netscape') < alert('Верно!'); >else

При чтении глаза сканируют код по вертикали. Блоки кода, занимающие несколько строк, воспринимаются гораздо легче, чем длинный горизонтальный набор инструкций.

Смысл оператора «вопросительный знак» ? – вернуть то или иное значение, в зависимости от условия. Пожалуйста, используйте его именно для этого. Когда вам нужно выполнить разные ветви кода – используйте if .

Задачи

if (строка с нулём)

Да, выведется.

Любая строка, кроме пустой (а строка "0" – не пустая), в логическом контексте становится true .

Можно запустить и проверить:

Название JavaScript

Используя конструкцию if..else , напишите код, который будет спрашивать: „Какое «официальное» название JavaScript?“

Если пользователь вводит «ECMAScript», то показать: «Верно!», в противном случае – отобразить: «Не знаете? ECMAScript!»

Источник

if. else

The if. else statement executes a statement if a specified condition is truthy. If the condition is falsy, another statement in the optional else clause will be executed.

Try it

Syntax

if (condition) statement1 // With an else clause if (condition) statement1 else statement2 

An expression that is considered to be either truthy or falsy.

Statement that is executed if condition is truthy. Can be any statement, including further nested if statements. To execute multiple statements, use a block statement ( < /* . */ >) to group those statements. To execute no statements, use an empty statement.

Statement that is executed if condition is falsy and the else clause exists. Can be any statement, including block statements and further nested if statements.

Читайте также:  Java throw exception import

Description

Multiple if. else statements can be nested to create an else if clause. Note that there is no elseif (in one word) keyword in JavaScript.

if (condition1) statement1 else if (condition2) statement2 else if (condition3) statement3 // … else statementN 

To see how this works, this is how it would look if the nesting were properly indented:

if (condition1) statement1 else if (condition2) statement2 else if (condition3) statement3 // … 

To execute multiple statements within a clause, use a block statement ( < /* . */ >) to group those statements.

if (condition)  statements1 > else  statements2 > 

Not using blocks may lead to confusing behavior, especially if the code is hand-formatted. For example:

function checkValue(a, b)  if (a === 1) if (b === 2) console.log("a is 1 and b is 2"); else console.log("a is not 1"); > 

This code looks innocent — however, executing checkValue(1, 3) will log "a is not 1". This is because in the case of dangling else, the else clause will be connected to the closest if clause. Therefore, the code above, with proper indentation, would look like:

function checkValue(a, b)  if (a === 1) if (b === 2) console.log("a is 1 and b is 2"); else console.log("a is not 1"); > 

In general, it is a good practice to always use block statements, especially in code involving nested if statements.

function checkValue(a, b)  if (a === 1)  if (b === 2)  console.log("a is 1 and b is 2"); > > else  console.log("a is not 1"); > > 

Do not confuse the primitive Boolean values true and false with truthiness or falsiness of the Boolean object. Any value that is not false , undefined , null , 0 , -0 , NaN , or the empty string ( "" ), and any object, including a Boolean object whose value is false , is considered truthy when used as the condition. For example:

const b = new Boolean(false); if (b)  console.log("b is truthy"); // "b is truthy" > 

Examples

Using if. else

if (cipherChar === fromChar)  result += toChar; x++; > else  result += clearChar; > 

Using else if

Note that there is no elseif syntax in JavaScript. However, you can write it with a space between else and if :

if (x > 50)  /* do something */ > else if (x > 5)  /* do something */ > else  /* do something */ > 

Using an assignment as a condition

You should almost never have an if. else with an assignment like x = y as a condition:

However, in the rare case you find yourself wanting to do something like that, the while documentation has a Using an assignment as a condition section with an example showing a general best-practice syntax you should know about and follow.

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 5, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Оцените статью