Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullish Coalescing operator in JavaScript

Tags:

javascript

How to this thing in better way.

this.state.updateItem?this.state.updateItem.unit:'Unit';

I have tried with this.state.updateItem.unit || 'Unit', but it found out that it will produce error since this.state.updateItem is NULL then it can't find any property of unit.

How to do it in better way?

like image 667
Jasson Harsojo Avatar asked Dec 10 '17 07:12

Jasson Harsojo


People also ask

What is Nullish coalescing operator in JavaScript?

The nullish coalescing operator ( ?? ) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined , and otherwise returns its left-hand side operand.

Does JavaScript have a null coalescing operator?

JavaScript now supports the nullish coalescing operator (??). It returns its right-hand-side operand when its left-hand-side operand is null or undefined , and otherwise returns its left-hand-side operand. Please check compatibility before using it.

What are Nullish values in JS?

In JavaScript, a nullish value is the value which is either null or undefined . Nullish values are always falsy.

What is 2 question marks in JS?

The JavaScript double question mark (??) operator is called the nullish coalescing operator and it provides a default value when a variable or an expression evaluates to null or undefined.


2 Answers

For now you have to do this like:

(this.state.updateItem || {}).unit || 'Unit'

There is a stage one proposal to ES (JavaScript) for optional chaining whereby we'll (eventually, hopefully) be able do do something like this:

this.state.updateItem?.unit || 'Unit'

And if you're doing babel you can use it now!:
https://www.npmjs.com/package/babel-plugin-transform-optional-chaining

Edit: The proposal is now in stage 4 (as of January 2020) and will be added into the JavaScript standard

like image 131
Faust Avatar answered Sep 21 '22 19:09

Faust


You can try with setting empty object as default value:

(this.state.updateItem || {}).unit || 'Unit'

unit will always either have value or be undefined.

like image 37
mickl Avatar answered Sep 22 '22 19:09

mickl