6

ES 12/2021 introduces new logical assignment operators

 3 years ago
source link: https://blog.saeloun.com/2021/06/17/es2021-logical-assignment-operator-and-or-nullish
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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 ES12
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 ES12
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 ES12/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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK