Javascript and or operator logical

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

В 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

Источник

Logical operators

There are four logical operators in JavaScript: || (OR), && (AND), ! (NOT), ?? (Nullish Coalescing). Here we cover the first three, the ?? operator is in the next article.

Although they are called “logical”, they can be applied to values of any type, not only boolean. Their result can also be of any type.

|| (OR)

The “OR” operator is represented with two vertical line symbols:

In classical programming, the logical OR is meant to manipulate boolean values only. If any of its arguments are true , it returns true , otherwise it returns false .

In JavaScript, the operator is a little bit trickier and more powerful. But first, let’s see what happens with boolean values.

There are four possible logical combinations:

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

As we can see, the result is always true except for the case when both operands are false .

If an operand is not a boolean, it’s converted to a boolean for the evaluation.

For instance, the number 1 is treated as true , the number 0 as false :

Most of the time, OR || is used in an if statement to test if any of the given conditions is true .

We can pass more conditions:

let hour = 12; let isWeekend = true; if (hour < 10 || hour >18 || isWeekend) < alert( 'The office is closed.' ); // it is the weekend >

OR «||» finds the first truthy value

The logic described above is somewhat classical. Now, let’s bring in the “extra” features of JavaScript.

The extended algorithm works as follows.

Given multiple OR’ed values:

result = value1 || value2 || value3;

The OR || operator does the following:

  • Evaluates operands from left to right.
  • For each operand, converts it to boolean. If the result is true , stops and returns the original value of that operand.
  • If all operands have been evaluated (i.e. all were false ), returns the last operand.

A value is returned in its original form, without the conversion.

In other words, a chain of OR || returns the first truthy value or the last one if no truthy value is found.

alert( 1 || 0 ); // 1 (1 is truthy) alert( null || 1 ); // 1 (1 is the first truthy value) alert( null || 0 || 1 ); // 1 (the first truthy value) alert( undefined || null || 0 ); // 0 (all falsy, returns the last value)

This leads to some interesting usage compared to a “pure, classical, boolean-only OR”.

    Getting the first truthy value from a list of variables or expressions. For instance, we have firstName , lastName and nickName variables, all optional (i.e. can be undefined or have falsy values). Let’s use OR || to choose the one that has the data and show it (or «Anonymous» if nothing set):

let firstName = ""; let lastName = ""; let nickName = "SuperCoder"; alert( firstName || lastName || nickName || "Anonymous"); // SuperCoder

Источник

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.

Источник

Читайте также:  Css not child element
Оцените статью