DEV Community

Cover image for How to effectively use logical operators in JavaScript
Emmanuel Fordjour  Kumah
Emmanuel Fordjour Kumah

Posted on • Updated on

How to effectively use logical operators in JavaScript

Hello World, in our previous post we learnt how to use the unary operators in JavaScript.

In this post, we will learn how you can use logical operators to make decision in your code.By the end of this post, you should be able to use the && ,! and || operators to make decisions in your code.

Let's get started.

What are Logical Operators?

Logical operators are very useful for comparing variables and taking some action based on the result of the comparison.
It allows developers to test for true or false values and do something based on the result.

  • If an expresion is true, we do this, if not, we can do that.

Logical operators are mainly used with Boolean values ( true or false values) and return Boolean values.However, they can also be used on non-Boolean values, returning a non-Boolean value.

In this article, we take a look at three main logical operators in JavaScript:

  • || (OR)
  • && (AND)
  • ! (NOT) Let's see the details

Using the Logical ! (NOT) operator.

In JavaScript, logical (NOT) operator is represented with an exclamation sign !. It's major use case is to reverse the value of a boolean

The logical ! operator turns a truthy value to a falsy value and vice versa

Syntax for Logical NOT !

let result = !value;
Enter fullscreen mode Exit fullscreen mode

When you apply the ! operator to a boolean value, it will convert the operand into the boolean type (eithertrue or false) and returns the reverse value

  • if the value of the operand is true, the ! operator will return the inverse of the value (false)
  • if the value of the operand is false, the ! operator will return the inverse of the value true.

Let's see an example below:

let result = true;
let isLoggedIn = false ;
console.log(!result);
console.log(!isLoggedIn)
Enter fullscreen mode Exit fullscreen mode

The output of the above will be

false
true
Enter fullscreen mode Exit fullscreen mode
  • The value of the result variable is true, so the ! operator will return the inverse of true ( which is false).
  • The value of the isLoggedIn variable is false, so the ! operator will return the inverse of false (which is true).

Applying the ! operator on non-boolean values

When you operate the ! on a non-boolean value, the ! operator will convert the given value to a boolean value and then negates it.
Let's see some examples

let firstName = "Emma"; /* Non boolean value */
console.log(!firstName)
Enter fullscreen mode Exit fullscreen mode

The output will be

false
Enter fullscreen mode Exit fullscreen mode
  • The value in the firstName variable is a truthy value, meaning the value is considered true when passed through a boolean function ( all non-empty strings are considered true)

  • The ! operator will then negate the value true returning false

All values are considered truthyexcept "", null, undefined, 0, and NaN , "", which are falsy values. Because these values are false, the ! operator will return the reverse which is true when operated on them.

Let's see some examples

console.log(!undefined)
console.log(!null)
console.log(!0)
console.log(!NaN)
console.log(!"")
Enter fullscreen mode Exit fullscreen mode

The output will be

true
true
true
true
true
Enter fullscreen mode Exit fullscreen mode

Using Double negation (!!)

When the double negation !! is used in our code, we are essentially using the logical NOT operator (!) twice to change a value to its boolean value.

Consider the example below:

let totalUsers = 20;
console.log(!!totalUsers) /* using the ! twice */
Enter fullscreen mode Exit fullscreen mode

Let's investigate what is happening:

  • The first ! will return the boolean value of the totalUsers and negate it.
  • Because the value of totalUsers is true , the first ! will negate true returning false.
  • The second ! then negates the result of false, (!false), returning the real boolean value of the totalUsers variable.

The output will then be

true
Enter fullscreen mode Exit fullscreen mode

In summary, we use the logical NOT (!) operator to** return the inverse or reverse of a boolean value**. The ! operator works on a single operand.

Using the Logical AND (&&) operator.

Another way of making decisions in programming is using the && operator.

The AND && operator returns true if both operands are true, otherwise, it returns false

Syntax for the && operator

let result = a && b
Enter fullscreen mode Exit fullscreen mode

Let's see what happens when we apply the && operator to two boolean values a, b.

  • if a has a value of true and b has a value of true, then a && b will be true
  • if a has a value of true and b has a value of false, then a && b will be false
  • if a has a value of false and b has a value of false, then a && b will be false
  • if a has a value of false and b has a value of true, then a && b will be false.

In simple terms:

console.log( true && true );   // true
console.log( false && true );  // false
console.log( true && false );  // false
console.log( false && false ); // false
Enter fullscreen mode Exit fullscreen mode

Let use the && operator in a conditional like the if() statement.

  • We have learnt that if the first operand evaluates to be true and the second operand evaluates to be true, then using the && operator will return true
  • With the if(condition), if the expression (condition) inside the brackets () returns true, then the statement after it will be evaluated.

Let's put all together with an example

let age = 20;
let isLoggedIn = true;

if(age && isLoggedIn){
    console.log("You can access this website")
}
Enter fullscreen mode Exit fullscreen mode

The output will be

You can access this website
Enter fullscreen mode Exit fullscreen mode
  • The expression (age && isLoggedIn) will return true since both values are truthy
  • Since the expression evaluates to be true, the code inside the {} will be executed.
  • However, should any of the operand be evaluated as false, the && operator will return false, making the result of the expression falseand the statement below will not be executed.

The result of the && operator will return true if both values are true otherwise it will return false.

Finding the first falsy value using multiple &&

Sometimes, we can use two or more && values in our code also known as a chain of && operators.
Consider the code below

let result = firstValue && secondValue && thirdValue; 
Enter fullscreen mode Exit fullscreen mode

The && operator will do the following:

  • Evaluates the values from left to right.
  • For each value, converts it to a boolean (true or false)
  • If the result is false, it stops executing and returns the original value of the operand
  • However, if all the values have been evaluted to be true (i.e all were truthy), it returns the last value.

Meaning, the && operator returns the first falsy value or the last value if no falsy value was found.

  • A **truthy **value is a value which can be converted to be true
  • A **falsy **value is a value which can be converted to be false

Let's see some examples

  • What will be the result of the && ?
let isLoggedIn = false;
let age= 18
let country = "Ghana";

console.log(isLoggedIn && age && country);
Enter fullscreen mode Exit fullscreen mode

The output will be

false
Enter fullscreen mode Exit fullscreen mode
  • The && operator returns the first falsy value. Since isLogged has a value of false the result of the expression above will be false.

  • What will be the result of the && ?

let isActive = true;
let users = 0;
let browser = "Google chrome"
console.log(isActive && users && browser)
Enter fullscreen mode Exit fullscreen mode

The output will be

0
Enter fullscreen mode Exit fullscreen mode
  • The && operator returns the first falsy value.
  • Since users has a value of 0 ( 0 is a falsy value), the output will be the value 0.

  • What will be the result of this && ?

let status = "Active";
let tweets = 203;
let career = "Frontend developer";
console.log(status && tweets && career)
Enter fullscreen mode Exit fullscreen mode

The output will be

Frontend developer
Enter fullscreen mode Exit fullscreen mode
  • The && operator returs the last value if all the values are truthy.
  • The career variable holds a truthy value, hence the last truthy value is Frontend developer.

Short-circuit evaluation using the && operator.

The && operator is short-circuited. This means

  • If the result of one value is found to be false, the && operator stops **and **returns the original value of that falsy operand; it will not check any of the remaining operands.

Consider the pseudo code below

(some falsy expression) && anotherExpr
Enter fullscreen mode Exit fullscreen mode
  • The anotherExpr part is never evaluated because the first operand (some falsy expression) is evaluated as false

  • Even if the anotherExpr is a function, that function will never be called.

Consider the example below

function firstExpr(){
    console.log("first expression");
    return false;
}

function anotherExpr(){
    console.log("Another expression");
    return true;

}

console.log(firstExpr() && anotherExpr());
Enter fullscreen mode Exit fullscreen mode

The output will be

first expression
false
Enter fullscreen mode Exit fullscreen mode

Do you know why ?

  • The call to firstExpr() logs first expression and returns `false'
  • Because the firstExpr() returns false the && operator short-circuits, hence, the anotherExpr() will not be called.
  • At any instance the expression is evaluated to be false, the rest of the expression will not be executed.

Using the logical OR || operator

JavaScript uses this symbol || to represent the OR operator.
You can apply the || operator on two values of any type.

Synxtax for the OR operator


let result = a || b;

Usually if a can be converted to true, we return a, else, return b.

Consider using the || operator on two boolean values

  • if a is true and b is true, then a || b will return true
  • if a is true and b is false, then a || b will return true.
  • if a is false and b is true, then a || b will return true
  • if a is false and b is false, then a|| b will return false.

From the above, there are four possible combinations

`

console.log(true || true); // true
console.log(true || false); // true
console.log(false || true); // true
console.log(false || false); // false

`

The || operator returns false if both values are false.

Most times, the || operator is used in an if statement to test if any of the given condition is true. If any of them returns true, the statement below will be executed.

Consider the code below:

`
let age = 20;

if(age == 18 || age > 18){
console.log("You can enter the club ")
}
`
The output will be


You can enter the club

Do you know why ?

  • The expression age == 18 is false, but age > 18 evaluates to be true.
  • Since one of the expression is true,we will basically have if(true) and the statement below can then be executed, given the output You can enter the club.

You can pass more conditions to the if statement.

Consider the code below;

`
let age = 20;
let hasRegistered = false;

if(hasRegistered || age == 18 || age > 18 ){
console.log("You can enter the club ")

}
`

  • Because there is at least one truthy value in the expression (i.e age > 18), the statement in the code block will be executed and the output will be You can enter the club.

Finding the first truthy value using the || operator.

Given multiple || values


let result = firstValue || secondValue || thirdValue

The || operator does the following :

  • Checks the operands from left to right
  • For each operand, converts it to boolean
  • If the result is true, it stops and returns the original value of that operand.
  • If all operands have been evaluated, and were all false, it returns the last operand
  • The value is returned in the 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:


let firstName = "";
let lastName = "";
let middleName = "Fordjour";
console.log(firstName || lastName || middleName || "Guest");

The output will be


Fordjour

  • The first truthy value in the expression is Fordjour
  • If there were no truthy values, then the output will be Guest (returning the last value )

Short-circuit evaluation of ||

The || operator is short-circuited. It means if the first value evaluates to be true, the || operator doesn't evaluate the second value

Consider the code below


let firstName = "Emmanuel"
console.log( "Hello ",firstName || "Guest");

The output will be


Hello Emmanuel

  • the firstName value is a truthy value, hence the Guest will not be evaluated.

Logical operator precedence

It is the order in which an operator is executed.

When we have mixed logical operators in an expression, the JavaScript engine will evaluate the operators based on this order

  1. Logical NOT(!)
  2. Logical AND (&&)
  3. Logical OR(||)

Quick Challenge

Test your understanding of logical operators.

What will be the result of the expression below ?


console.log( null || 2 && 3 || 4 );

Find out which of the console,log's will be executed

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


if (-1 || 0) console.log( 'first' );
if (-1 && 0) console.log( 'second' );
if (null || -1 && 1) console.log( 'third' );

Comment your answer below.

In Summary

  • The ! operator negates a boolean value
  • The && returns true if **both **operands are true
  • The || returns true if **one **of the operands is true

Kindly share on your social networks if you find the post valuable Written with love 😍 from 🇬🇭 Ghana.

Me daa se (Thank you)

Top comments (0)