DEV Community

Cover image for What you should know about the Logical Assignment Operators in JavaScript
Emmanuel Fordjour  Kumah
Emmanuel Fordjour Kumah

Posted on

What you should know about the Logical Assignment Operators in JavaScript

Hello World, every year, new features get added to the JavaScript language.This enables developers write better code which translates into awesome products.

In 2021, the Logical assignment operators were added to the language. Its main objective is to assign values to variables.
In this post, we will learn how to effectively utilize the logical assignment operators. Let's get started.

The Logical assignment operators

ES2021 introduced three logical assignment operators:

  • Logical OR assignment operator (||=)
  • Logical AND assignment operator (&&=)
  • Nullish coalesing assignment operator (??=)

The Logical assignment operators combine the logical operators and assignment expression.
If you have forgotten what Logical operators are, here is my post on Logical Operators to help refresh your mind.

Alright, now let's discuss the Logical OR assignment operator (||=)

What is the logical OR assignment operator

The logical OR assignment operator (||=) accepts two operands and assigns the right operand to the left operand if the left operand is falsy

The syntax is as below

x ||= y
Enter fullscreen mode Exit fullscreen mode

In the syntax, the ||= will only assign the value of y to x if x is falsy.

Let's take a look at the || operator first.
The Logical OR operator || returns the *first *truthy value in an expression.

Consider an example below

let firstName = "";
let noName = "Guest"

console.log(firstName || noName);
Enter fullscreen mode Exit fullscreen mode

The output will be Guest.

  • In the example above, the firstName variable is an empty string "" , and the noName variable is a string ( a string stores a sequence of characters).
  • Empty strings "" are considered falsy values while non-empty strings(eg. "emma") are truthy values.
  • Because the || operator returns the first truthy value, the value stored in the noName variable (ie.Guest) will logged to the console.

Note that : 0, null, undefined, NaN and "" are classified as falsy values.

Assigning a value to a variable using the ||= operator.

Consider a situation where you want to assign a truthy value to a variable storing a falsy value

Let's see how you can achieve that using the logical OR assignment operator (||=)

You can do this (long method)

let firstName=""
let noName="Guest"

//assign the "Guest" value to the firstName variable 
firstName = firstName || noName
Enter fullscreen mode Exit fullscreen mode

Let's understand the code above

  • The expression on the right : firstName || noName is evaluated first.
  • Since the || operator returns the first truthy value, it will return the value Guest
  • Using the = (assignment operator), the value Guest is then assigned to the firstName variable which has a falsy value
  • Now, anytime we console.log(firstName), we get the value Guest

The example above can be simplified using the logical OR assignment operator (||=).

// long form 
firstName = firstName || noName

//using the ||= syntax

firstName ||= noName;
Enter fullscreen mode Exit fullscreen mode

Example 2

let age; // age is undefined 

age ||=28;
console.log('The value of age is now ', age )
Enter fullscreen mode Exit fullscreen mode

The output will be

The value of age is now 28
Enter fullscreen mode Exit fullscreen mode

-The truthy value of 28 will be assigned to the age variable which has a falsy value

  • The age now has a value of 28

Example 3

You can also assign a truthy value to a property in an object if the property is falsy.
Take a look at the code below

let userDetails= {
firstName: "Emmanuel",
userName:"" // userName stores a falsy value
}

//using the ||= 
userDetails.userName ||="emma"
console.log('The username is now ', userDetails.userName)
Enter fullscreen mode Exit fullscreen mode

The output will be

The username is now emma
Enter fullscreen mode Exit fullscreen mode

In the example above

  • The || operator evaluates the expression and returns the firsty truthy value ("emma")
  • The truthy value is now assigned to the userDetails.username property since userDetails.username is falsy

If the first operand is a truthy value, the logical OR assignment operator (||=) will** not assign the value of the second operand to the first. **

Consider the code below

let userDetails = {
    firstName: "Emmanuel",
    userName : "efk"
}

userDetails.userName ||="emma";

console.log('The username is now ', userDetails.userName)
Enter fullscreen mode Exit fullscreen mode

The output will be

The username is now efk
Enter fullscreen mode Exit fullscreen mode
  • Because the userDetails.userName property is truthy, the second operand was not evaluated

In summary, the x ||= y will assign the value of y to x if x is falsy.

Using the Logical AND assignment operator (&&=)

Sometimes you may want to assign a value to a variable even if the initial variable has a value. This is where the logical AND assignment operator (&&=) comes in.

What is the logical AND assignment operator ?

The logical AND assignment operator only assigns y to x if x is truthy

*The syntax is as below *

x &&= y
Enter fullscreen mode Exit fullscreen mode
  • if the operand on the left side is truthy, the value of y is then assigned to x

Let's see how this was done previously

let firstName = "Emmanuel"
let userName = "efk"

if(firstName){
    firstName = userName
}
console.log(firstName)
Enter fullscreen mode Exit fullscreen mode

The output will be efk.

  • The if evaluates the condition in the parenthesis ()
  • If the condition is true then the expression inside the curly braces {} gets evaluated
  • Because the firstName is truthy, we assign the value of userName to firstName.

Using &&= in the same example as above

let firstName = "Emmanuel"
let userName = "efk"

firstName &&= userName
console.log("the first name is now ", firstName)
Enter fullscreen mode Exit fullscreen mode

The output will be

the first name is now  efk
Enter fullscreen mode Exit fullscreen mode
  • Because firstName is a truthy value, the value of userName is now assigned to firstName

The &&= operator is very useful for changing values. Consider the example below

Example 2

let userDetails = {
id: 1,
firstName: "Emmanuel",
lastName: "Fo"
}

userDetails.lastName &&="Fordjour"

console.log(userDetails)
Enter fullscreen mode Exit fullscreen mode

The output will be

{id: 1, firstName: 'Emmanuel', lastName: 'Fordjour'}
Enter fullscreen mode Exit fullscreen mode
  • userDetails.lastName is a truthy value hence the right operand Fordjour is assigned to it.

Example 3

In the code below, we given an object, and our task is to change the id to a random number between 1 and 10.

Let's see how that can be done using the &&=

let userDetails = {
id: 1, 
firstName: "Emmanuel"
}

//generate random number 
function genRandomNum(){
return (Math.floor((Math.random() * 10 ) + 1))
}

//assign the random number to the userDetails.id
userDetails.id &&= genRandomNum()
console.log("the id is now ", userDetails.id)
Enter fullscreen mode Exit fullscreen mode

The output will vary depending on the random number returned, here is an example.

the id is now  3
Enter fullscreen mode Exit fullscreen mode

In summary, the &&= operator assigns the value of the right operand to the left operand if the left operand is truthy

The nullish coalescing assignment operator (??=)

The nullish coalescing assignment operator only assigns y to x if x is null or undefined.

The syntax is as below

x ??= y
Enter fullscreen mode Exit fullscreen mode

Let's see how to use the nullish coalescing assignment operator

Example 1

let firstName; //undefined

firstName ??="Emmanuel";

console.log('first name is now ', firstName)
Enter fullscreen mode Exit fullscreen mode

The output will be

first name is now  Emmanuel
Enter fullscreen mode Exit fullscreen mode
  • The firstName variable is undefined
  • We now assign the value of the right operand to firstName
  • firstName now has the value of Emmanuel.

Example 2

Adding a missing property to an object

let userDetails = {
    firstName: "Emmanuel"
}
userDetails.userName ??="Guest";

console.log(userDetails)
Enter fullscreen mode Exit fullscreen mode

The output will be

{firstName: 'Emmanuel', userName: 'Guest'}
Enter fullscreen mode Exit fullscreen mode
  • The userDetails.userName is undefined hence nullish
  • The nullish coalescing assignment operator ??= then assigns the string Guest to the userDetails.userName
  • Now the userDetails object has property userName.

In summary

  • The logical OR assignment (x ||= y) operator only assigns y to x if x is falsy.
  • The logical AND assignment (x &&=y) operator will assign y to x if x is truthy
  • The nullish coalescing assignment operator will assign y to x if x is undefined or null.

I trust you have learnt something valuable to add to your coding repository.
Is there anything that wasn't clear to you ? I would love to read your feedback on the article.

Writing with love from Ghana. Me daa se (Thank you)

Top comments (1)

Collapse
 
elliemark profile image
Ellie Mark • Edited

Logical operators are expressions used to make conditions. It might be confusing at first but once you practice you will understand. After all, you don't learn coding without practice. I had to use NVQ assignment writing help which has been a life saver for me.