JavaScript logical AND operator example

JavaScript: Logical Operators — AND, OR, NOT

The logical operators used in Javascript are listed below:

Operator Usage Description
Logical AND ( && ) a && b is true if both a and b are true.
Logical OR ( || ) a || b is true if either a or b is true.
Logical NOT ( ! ) !a is true if a is not true.

JavaScript Logical AND operator (&&)

The following conditions are true :

The following conditions are false :

This above pictorial helps you to understand the concept of LOGICAL AND operation with an analogy of taps and water.

In fig.-1 of the picture, both of the taps are closed, so the water is not flowing down. Which explains that if both of conditions are FALSE or 0, the return is FALSE or 0.

In fig.-2 of the picture, one of the taps are closed, even then, the water is not flowing down. Which explains that even if any of conditions are FALSE or 0, the return is FALSE or 0.

fig.-3 of the picture resembles CASE -2.

In fig.-4 of the picture, both of the taps are open, so the water is flowing down. Which explains that if both of conditions are TRUE or 1, the return is TRUE or 1.

So we can conclude that if and only if, both of the conditions are TRUE or 1, LOGICAL AND operations returns TRUE or 1.

The following web document demonstrates the use of AND operator (&&).

     h1 

JavaScript equal operator (==) example

function viewOutput() < 'use strict'; var no = document.getElementById('no').value; if( no>= 5 && no else < var newParagraph1 = document.createElement("p"); //creates a new paragraph element var newText1 = document.createTextNode('Wrong input'); //creates text along with ouput to be displayed newParagraph1.appendChild(newText1); //created text is appended to the paragraph element created document.body.appendChild(newParagraph1); // created paragraph and text along with output is appended to the document body >> 

JavaScript Logical OR operator (||)

The following conditions are true :

The following conditions are false :

The above pictorial helps you to understand the concept of LOGICAL OR operation with an analogy of taps and water.

In fig.-1 of the picture, both of the taps are closed, so the water is not flowing down. Which explains that if both of conditions are FALSE or 0, the return is FALSE or 0.

In fig.-2 of the picture, one of the taps are closed, and we can see that the water is flowing down. Which explains that if any of conditions are TRUE or 1, the return is TRUE or 1.

fig.-3 of the picture resembles CASE -2.

In fig.-4 of the picture, both of the taps are open, so the water is flowing down. Which explains that if both of conditions are TRUE or 1, the return is TRUE or 1.

So we can conclude that in LOGICAL OR operation if any of the conditions are true, the output is TRUE or 1.

The following web document demonstrates the use of OR operator (||).

    h1 

JavaScript logical OR operator example

function viewOutput() < 'use strict'; var no = document.getElementById('no').value; if( no20 ) < var newParagraph = document.createElement("p"); //creates a new paragraph element var newText = document.createTextNode('Value of input is less than 5 or greater than 20'); //creates text along with ouput to be displayed newParagraph.appendChild(newText); //created text is appended to the paragraph element created document.body.appendChild(newParagraph); // created paragraph and text along with output is appended to the document body >else < var newParagraph1 = document.createElement("p"); //creates a new paragraph element var newText1 = document.createTextNode('Wrong input'); //creates text along with ouput to be displayed newParagraph1.appendChild(newText1); //created text is appended to the paragraph element created document.body.appendChild(newParagraph1); // created paragraph and text along with output is appended to the document body >> 

JavaScript Logical NOT operator (!)

     h1 

JavaScript logical NOT operator example

var a = 20; var b = 5; var newParagraph = document.createElement("p"); //creates a new paragraph element var newText = document.createTextNode('Value of a = '+a+' b = '+b); //creates text along with ouput to be displayed newParagraph.appendChild(newText); //created text is appended to the paragraph element created document.body.appendChild(newParagraph); // created paragraph and text along with output is appended to the document body if( a != b ) < var newParagraph1 = document.createElement("p"); //creates a new paragraph element var newText1 = document.createTextNode('a is not equal to b [ != operator ]'); //creates text along with ouput to be displayed newParagraph1.appendChild(newText1); //created text is appended to the paragraph element created document.body.appendChild(newParagraph1); // created paragraph and text along with output is appended to the document body >else < var newParagraph2 = document.createElement("p"); //creates a new paragraph element var newText2 = document.createTextNode('a is equal to b.'); //creates text along with ouput to be displayed newParagraph2.appendChild(newText2); //created text is appended to the paragraph element created document.body.appendChild(newParagraph2); // created paragraph and text along with output is appended to the document body > 

Want to Test your JavaScript skill ?

Want to Practice JavaScript exercises ?

Test your Programming skills with w3resource’s quiz.

Читайте также:  Css div menu fixed

Follow us on Facebook and Twitter for latest update.

JavaScript: Tips of the Day

How to append something to an array?

Use the Array.prototype.push method to append values to an array:

// initialize array var arr = [ "Hi", "Hello", "Bonjour" ]; // append new value to the array arr.push("Hola"); console.log(arr);

You can use the push() function to append more than one value to an array in a single call:

// initialize array var arr = [«Hi», «Hello», «Bonjour», «Hola»]; // append multiple values to the array arr.push(«Salut», «Hey»); // display all values for (var i = 0; i

If you want to add the items of one array to another array, you can use firstArray.concat(secondArray):

var arr = [ "apple", "banana", "cherry" ]; arr = arr.concat([ "dragonfruit", "elderberry", "fig" ]); console.log(arr);

Just an addition to this answer if you want to append any value to the start of an array that means to the first index then you can use Array.prototype.unshift for this purpose.

var arr = [1, 2, 3]; arr.unshift(0); console.log(arr);

It also supports appending multiple values at once just like push.

  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

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

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

Читайте также:  Php если содержит регулярные выражения

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

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

|| (ИЛИ)

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

Традиционно в программировании ИЛИ предназначено только для манипулирования булевыми значениями: в случае, если какой-либо из аргументов 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

Источник

Читайте также:  Java калькуляторы для мобильного

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

Источник

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