Javascript conditional operator and or

Logical OR (||)

The logical OR ( || ) (logical disjunction) operator for a set of operands is true if and only if one or more of its operands is true. It is typically used with boolean (logical) values. When it is, it returns a Boolean value. However, the || operator actually returns the value of one of the specified operands, so if this operator is used with non-Boolean values, it will return a non-Boolean value.

Try it

Syntax

Description

If x can be converted to true , returns x ; else, returns y .

If a value can be converted to true , the value is so-called truthy. If a value can be converted to false , the value is so-called falsy.

Examples of expressions that can be converted to false are:

Even though the || operator can be used with operands that are not Boolean values, it can still be considered a boolean operator since its return value can always be converted to a boolean primitive. To explicitly convert its return value (or any expression in general) to the corresponding boolean value, use a double NOT operator or the Boolean constructor.

Short-circuit evaluation

The logical OR expression is evaluated left to right, it is tested for possible «short-circuit» evaluation using the following rule:

(some truthy expression) || expr is short-circuit evaluated to the truthy expression.

Short circuit means that the expr part above is not evaluated, hence any side effects of doing so do not take effect (e.g., if expr is a function call, the calling never takes place). This happens because the value of the operator is already determined after the evaluation of the first operand. See example:

function A()  console.log("called A"); return false; > function B()  console.log("called B"); return true; > console.log(B() || A()); // Logs "called B" due to the function call, // then logs true (which is the resulting value of the operator) 

Operator precedence

The following expressions might seem equivalent, but they are not, because the && operator is executed before the || operator (see operator precedence).

true || false && false; // returns true, because && is executed first (true || false) && false; // returns false, because grouping has the highest precedence 

Examples

Using OR

The following code shows examples of the || (logical OR) operator.

true || true; // t || t returns true false || true; // f || t returns true true || false; // t || f returns true false || 3 === 4; // f || f returns false "Cat" || "Dog"; // t || t returns "Cat" false || "Cat"; // f || t returns "Cat" "Cat" || false; // t || f returns "Cat" "" || false; // f || f returns false false || ""; // f || f returns "" false || varObject; // f || object returns varObject 

Note: If you use this operator to provide a default value to some variable, be aware that any falsy value will not be used. If you only need to filter out null or undefined , consider using the nullish coalescing operator.

Conversion rules for booleans

Converting AND to OR

The following operation involving booleans:

Converting OR to AND

The following operation involving booleans:

Removing nested parentheses

As logical expressions are evaluated left to right, it is always possible to remove parentheses from a complex expression following some rules.

The following composite operation involving booleans:

!(!bCondition1 || !bCondition2 && !bCondition3) 

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 Jul 7, 2023 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.

Источник

Логические операторы

В JavaScript есть четыре логических оператора: || (ИЛИ), && (И) и ! (НЕ), ?? (Оператор нулевого слияния). Здесь мы рассмотрим первые три, оператор ?? будет в следующей статье.

Несмотря на своё название, данные операторы могут применяться к значениям любых типов. Полученные результаты также могут иметь различный тип.

Давайте рассмотрим их подробнее.

|| (ИЛИ)

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

Традиционно в программировании ИЛИ предназначено только для манипулирования булевыми значениями: в случае, если какой-либо из аргументов true , он вернёт true , в противоположной ситуации возвращается false .

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

Существует всего четыре возможные логические комбинации:

alert( true || true ); // true alert( false || true ); // true alert( true || false ); // true alert( false || false ); // false

Как мы можем наблюдать, результат операций всегда равен true , за исключением случая, когда оба аргумента false .

Если значение не логического типа, то оно к нему приводится в целях вычислений.

Например, число 1 будет воспринято как true , а 0 – как false :

Обычно оператор || используется в if для проверки истинности любого из заданных условий.

Можно передать и больше условий:

let hour = 12; let isWeekend = true; if (hour < 10 || hour >18 || isWeekend) < alert( 'Офис закрыт.' ); // это выходной >

ИЛИ «||» находит первое истинное значение

Описанная выше логика соответствует традиционной. Теперь давайте поработаем с «дополнительными» возможностями JavaScript.

Расширенный алгоритм работает следующим образом.

При выполнении ИЛИ || с несколькими значениями:

result = value1 || value2 || value3;

Оператор || выполняет следующие действия:

  • Вычисляет операнды слева направо.
  • Каждый операнд конвертирует в логическое значение. Если результат true , останавливается и возвращает исходное значение этого операнда.
  • Если все операнды являются ложными ( false ), возвращает последний из них.

Значение возвращается в исходном виде, без преобразования.

Другими словами, цепочка ИЛИ || возвращает первое истинное значение или последнее, если такое значение не найдено.

alert( 1 || 0 ); // 1 alert( true || 'no matter what' ); // true alert( null || 1 ); // 1 (первое истинное значение) alert( null || 0 || 1 ); // 1 (первое истинное значение) alert( undefined || null || 0 ); // 0 (поскольку все ложно, возвращается последнее значение)

Это делает возможным более интересное применение оператора по сравнению с «чистым, традиционным, только булевым ИЛИ».

    Получение первого истинного значения из списка переменных или выражений. Представим, что у нас имеется ряд переменных, которые могут содержать данные или быть null/undefined . Как мы можем найти первую переменную с данными? С помощью || :

let currentUser = null; let defaultUser = "John"; let name = currentUser || defaultUser || "unnamed"; alert( name ); // выбирается "John" – первое истинное значение
let x; true || (x = 1); alert(x); // undefined, потому что (x = 1) не вычисляется

Если бы первый аргумент имел значение false , то || приступил бы к вычислению второго и выполнил операцию присваивания:

let x; false || (x = 1); alert(x); // 1

&& (И)

Оператор И пишется как два амперсанда && :

В традиционном программировании И возвращает true , если оба аргумента истинны, а иначе – false :

alert( true && true ); // true alert( false && true ); // false alert( true && false ); // false alert( false && false ); // false

Источник

Читайте также:  CSS Positioning
Оцените статью