ES 12/2021 introduces new logical assignment operators

ECMAScript 2021 Language Specification recently reached to a release candidate, introducing many new JavaScript language features.

One of the new additions are logical assignment operators (??=, &&=, ||=) which combine the logical operations(&&, || or ??) with assignment(=).

Let’s take a look at some examples of these and their use cases.

Logical nullish assignment (??=)

Logical nullish assignment operator assigns a value to a variable if it is currently nullish (undefined or null).

let currentUserId;

console.log(currentUserId);
// undefined

// Old way
if(currentUserId == undefined || currentUserId == null) {
  currentUserId = 42;
}

or

currentUserId ?? (currentUserId = 42);

console.log(currentUserId);
// 42

//With ES2021
currentUserId ??= 42;

console.log(currentUserId);
// 42

This can come in handy in cases where we’d want to fill out missing properties or options.

const filterProducts = (filterOptions ={}) => {
  filterOptions.filterColor ??= 'black';
  filterOptions.filterSoldOut ??= true;
  console.log(filterOptions);
  // Use filterOptions here
}

filterProducts();
// {filterColor: 'black', filterSoldOut: true};

filterProducts({filterColor: 'blue'});
// {filterColor: 'blue', filterSoldOut: true}

Logical AND assignment (&&=)

Logical AND assignment operator assigns a value to a variable if it is currently truthy.

This helps us simplify some of the checks for presence/truthiness before assigning values.

let authorizedUser = {id: 42, name: "Vipul"};

console.log(authorizedUser);
// {id: 42, name: "Vipul"}

// Old way
if(authorizedUser) {
  authorizedUser = {...authorizedUser, admin: true};
}

console.log(authorizedUser);
// {id: 42, name: "Vipul", admin: true}

//With ES2021
authorizedUser &&= {...authorizedUser, admin: true} ;

console.log(authorizedUser);
// {id: 42, name: "Vipul", admin: true}

Logical OR assignment (||=)

Logical OR assignment operation assigns a value to a variable if it is currently falsy.

Same as logical AND, this helps us simplify some of the checks for presence/truthiness before assigning values.

let currentUser = {id: 42, name: "Vipul"};

console.log(currentUser);
// {id: 42, name: "Vipul"}

// Old way
if(!currentUser.avatarImage) {
  currentUser.avatarImage = "https://via.placeholder.com/150" ;
}

console.log(authorizedUser);
// {id: 42, name: "Vipul", admin: true}

currentUser.avatarImage ||= "https://via.placeholder.com/150" ;

console.log(currentUser);
# {id: 42, name: "Vipul", avatarImage: "https://via.placeholder.com/150"}

Using ES2021 features in codebase

The new ES2021 features are supported by recent versions of major browsers.

To enable these features in old browsers, we need to do the below setup.

Install Babel packages:

  npm install --save-dev @babel/core @babel/cli @babel/preset-env
  npm install core-js

  or

  yarn add -D @babel/core @babel/cli @babel/preset-env
  yarn add core-js

Create the babel.config.json file at the root of the project.

{
    "presets": [
        [
            "@babel/preset-env",
            {
                "useBuiltIns": "usage",
                "corejs": {
                    "version": "3.8",
                    "proposals": true
                }
            }
        ]
    ]
}

Create a .browserlistrc file at the root of the project to

specify the target browsers for Babel to transform code in -

  defaults
  maintained node versions

Run the below command.

  ./node_modules/.bin/babel src --out-dir lib

It will transform the files in the src folder into a compatible version for old browsers and output in the lib folder.

Summary

The newly added logical assignment operators, help us simplify conditional assignments and evaluations, in a better way.

Need help on your Ruby on Rails or React project?

Join Our Newsletter