0% found this document useful (0 votes)
150 views11 pages

Logical Operators: The Javascript Language Javascript Fundamentals

Uploaded by

Saleem Shan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
150 views11 pages

Logical Operators: The Javascript Language Javascript Fundamentals

Uploaded by

Saleem Shan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

2/25/2021 Logical operators

 EPUB/PDF 👤 
EN

 → The JavaScript language → JavaScript Fundamentals

 2nd February 2021

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.

Let’s see the details.

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

1 result = a || b;

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:

 ✍
1 alert( true || true ); // true
2 alert( false || true ); // true
3 alert( true || false ); // true
4 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 :

 ✍
1 if (1 || 0) { // works just like if( true || false )
2 alert( 'truthy!' );
https://javascript.info/logical-operators 1/11
2/25/2021 Logical operators

3 }

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

For example:

 ✍
1 let hour = 9;
2
3 if (hour < 10 || hour > 18) {
4 alert( 'The office is closed.' );
5 }

We can pass more conditions:

 ✍
1 let hour = 12;
2 let isWeekend = true;
3
4 if (hour < 10 || hour > 18 || isWeekend) {
5 alert( 'The office is closed.' ); // it is the weekend
6 }

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:

1 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.

For instance:

https://javascript.info/logical-operators 2/11
2/25/2021 Logical operators

1 alert( 1 || 0 ); // 1 (1 is truthy)  ✍
2
3 alert( null || 1 ); // 1 (1 is the first truthy value)
4 alert( null || 0 || 1 ); // 1 (the first truthy value)
5
6 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”.

1. 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):

 ✍
1 let firstName = "";
2 let lastName = "";
3 let nickName = "SuperCoder";
4
5 alert( firstName || lastName || nickName || "Anonymous"); // SuperCoder

If all variables were falsy, "Anonymous" would show up.

2. Short-circuit evaluation.

Another feature of OR || operator is the so-called “short-circuit” evaluation.

It means that || processes its arguments until the first truthy value is reached, and then the value is returned
immediately, without even touching the other argument.

That importance of this feature becomes obvious if an operand isn’t just a value, but an expression with a side
effect, such as a variable assignment or a function call.

In the example below, only the second message is printed:

 ✍
1 true || alert("not printed");
2 false || alert("printed");

In the first line, the OR || operator stops the evaluation immediately upon seeing true , so the alert isn’t
run.

Sometimes, people use this feature to execute commands only if the condition on the left part is falsy.

&& (AND)
The AND operator is represented with two ampersands && :
https://javascript.info/logical-operators 3/11
2/25/2021 Logical operators

1 result = a && b;

In classical programming, AND returns true if both operands are truthy and false otherwise:

 ✍
1 alert( true && true ); // true
2 alert( false && true ); // false
3 alert( true && false ); // false
4 alert( false && false ); // false

An example with if :

 ✍
1 let hour = 12;
2 let minute = 30;
3
4 if (hour == 12 && minute == 30) {
5 alert( 'The time is 12:30' );
6 }

Just as with OR, any value is allowed as an operand of AND:

 ✍
1 if (1 && 0) { // evaluated as true && false
2 alert( "won't work, because the result is falsy" );
3 }

AND “&&” finds the first falsy value


Given multiple AND’ed values:

1 result = value1 && value2 && value3;

The AND && operator does the following:

● Evaluates operands from left to right.


● For each operand, converts it to a boolean. If the result is false , stops and returns the original value of that
operand.
● If all operands have been evaluated (i.e. all were truthy), returns the last operand.

In other words, AND returns the first falsy value or the last value if none were found.

https://javascript.info/logical-operators 4/11
2/25/2021 Logical operators

The rules above are similar to OR. The difference is that AND returns the first falsy value while OR returns the first
truthy one.

Examples:

 ✍
1 // if the first operand is truthy,
2 // AND returns the second operand:
3 alert( 1 && 0 ); // 0
4 alert( 1 && 5 ); // 5
5
6 // if the first operand is falsy,
7 // AND returns it. The second operand is ignored
8 alert( null && 5 ); // null
9 alert( 0 && "no matter what" ); // 0

We can also pass several values in a row. See how the first falsy one is returned:

 ✍
1 alert( 1 && 2 && null && 3 ); // null

When all values are truthy, the last value is returned:

 ✍
1 alert( 1 && 2 && 3 ); // 3, the last one

 Precedence of AND && is higher than OR ||


The precedence of AND && operator is higher than OR || .

So the code a && b || c && d is essentially the same as if the && expressions were in parentheses: (a &&
b) || (c && d) .

https://javascript.info/logical-operators 5/11
2/25/2021 Logical operators

⚠ Don’t replace if with || or &&


Sometimes, people use the AND && operator as a "shorter way to write if ".

For instance:

 ✍
1 let x = 1;
2
3 (x > 0) && alert( 'Greater than zero!' );

The action in the right part of && would execute only if the evaluation reaches it. That is, only if (x > 0) is
true.

So we basically have an analogue for:

 ✍
1 let x = 1;
2
3 if (x > 0) alert( 'Greater than zero!' );

Although, the variant with && appears shorter, if is more obvious and tends to be a little bit more readable.
So we recommend using every construct for its purpose: use if if we want if and use && if we want AND.

! (NOT)
The boolean NOT operator is represented with an exclamation sign ! .

The syntax is pretty simple:

1 result = !value;

The operator accepts a single argument and does the following:

1. Converts the operand to boolean type: true/false .


2. Returns the inverse value.

For instance:

 ✍
1 alert( !true ); // false
2 alert( !0 ); // true

A double NOT !! is sometimes used for converting a value to boolean type:

https://javascript.info/logical-operators 6/11
2/25/2021 Logical operators

 ✍
1 alert( !!"non-empty string" ); // true
2 alert( !!null ); // false

That is, the first NOT converts the value to boolean and returns the inverse, and the second NOT inverses it again. In
the end, we have a plain value-to-boolean conversion.

There’s a little more verbose way to do the same thing – a built-in Boolean function:

 ✍
1 alert( Boolean("non-empty string") ); // true
2 alert( Boolean(null) ); // false

The precedence of NOT ! is the highest of all logical operators, so it always executes first, before && or || .

✔ Tasks

What's the result of OR? 


importance: 5

What is the code below going to output?

1 alert( null || 2 || undefined );

solution

What's the result of OR'ed alerts? 


importance: 3

What will the code below output?

1 alert( alert(1) || 2 || alert(3) );

solution

What is the result of AND? 


importance: 5

What is this code going to show?


https://javascript.info/logical-operators 7/11
2/25/2021 Logical operators

1 alert( 1 && null && 2 );

solution

What is the result of AND'ed alerts? 


importance: 3

What will this code show?

1 alert( alert(1) && alert(2) );

solution

The result of OR AND OR 


importance: 5

What will the result be?

1 alert( null || 2 && 3 || 4 );

solution

Check the range between 


importance: 3

Write an if condition to check that age is between 14 and 90 inclusively.

“Inclusively” means that age can reach the edges 14 or 90 .

solution

Check the range outside 


importance: 3

Write an if condition to check that age is NOT between 14 and 90 inclusively.

Create two variants: the first one using NOT ! , the second one – without it.
https://javascript.info/logical-operators 8/11
2/25/2021 Logical operators

solution

A question about "if" 

importance: 5

Which of these alert s are going to execute?

What will the results of the expressions be inside if(...) ?

1 if (-1 || 0) alert( 'first' );


2 if (-1 && 0) alert( 'second' );
3 if (null || -1 && 1) alert( 'third' );

solution

Check the login 


importance: 3

Write the code which asks for a login with prompt .

If the visitor enters "Admin" , then prompt for a password, if the input is an empty line or Esc – show “Canceled”,
if it’s another string – then show “I don’t know you”.

The password is checked as follows:

● If it equals “TheMaster”, then show “Welcome!”,


● Another string – show “Wrong password”,
● For an empty string or cancelled input, show “Canceled”

The schema:

Begin

Who's there?

Cancel Other Admin

C l d
https://javascript.info/logical-operators
Id 't k 9/11
2/25/2021 Logical operators
Canceled I don't know you

Password?

Cancel Other TheMaster

Canceled Wrong password Welcome!

Please use nested if blocks. Mind the overall readability of the code.

Hint: passing an empty input to a prompt returns an empty string '' . Pressing ESC during a prompt returns
null .

Run the demo

solution

 Previous lesson Next lesson



Share    Tutorial map

Advance your skils with video courses on JavaScript and Frameworks. 

 Comments
● If you have suggestions what to improve - please submit a GitHub issue or a pull request instead of
commenting.
● If you can't understand something in the article – please elaborate.
● To insert few words of code, use the <code> tag, for several lines – wrap them in <pre> tag, for more
than 10 lines – use a sandbox (plnkr, jsbin, codepen…)

https://javascript.info/logical-operators 10/11
2/25/2021 Logical operators

141 Comments Javascript.info 🔒 Disqus' Privacy Policy 


1 Login

 Recommend 20 t Tweet f Share Sort by Best

Join the discussion…

LOG IN WITH
OR SIGN UP WITH DISQUS ?

Name

Farid • a year ago


let login = prompt("Who's there? " + " Answer : ((Admin))"); // Admin Question
let usr = "Admin"; // Admin
let pwd = "TheMaster"; // Password
if (login == false || login == null) {
// Empty feild || null is cancel button or Esc
alert("Canceled"); // Message
} else if (login != usr) {
// if Admin is have wrong value

© 2007—2021  Ilya Kantorabout the projectcontact usterms of usage


privacy policy

https://javascript.info/logical-operators 11/11

You might also like