Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null-safe property access (and conditional assignment) in ES6/2015

Is there a null-safe property access (null propagation / existence) operator in ES6 (ES2015/JavaScript.next/Harmony) like ?. in CoffeeScript for example? Or is it planned for ES7?

var aThing = getSomething() ... aThing = possiblyNull?.thing 

This will be roughly like:

if (possiblyNull != null) aThing = possiblyNull.thing 

Ideally the solution should not assign (even undefined) to aThing if possiblyNull is null

like image 452
ᅙᄉᅙ Avatar asked Aug 21 '15 11:08

ᅙᄉᅙ


People also ask

What is null safety Javascript?

Null safety prevents errors that result from unintentional access of variables set to null . For example, if a method expects an integer but receives null , your app causes a runtime error. This type of error, a null dereference error, can be difficult to debug.

Should I use Optional chaining?

You can use optional chaining when attempting to call a method which may not exist. This can be helpful, for example, when using an API in which a method might be unavailable, either due to the age of the implementation or because of a feature which isn't available on the user's device.

What is optional chaining in JS?

Optional chaining is a safe and concise way to perform access checks for nested object properties. The optional chaining operator ?. takes the reference to its left and checks if it is undefined or null. If the reference is either of these nullish values, the checks will stop and return undefined.


1 Answers

Update (2022-01-13): Seems people are still finding this, here's the current story:

  • Optional Chaining is in the specification now (ES2020) and supported by all modern browsers, more in the archived proposal: https://github.com/tc39/proposal-optional-chaining
  • babel-preset-env: If you need to support older environments that don't have it, this is probably what you want https://babeljs.io/docs/en/babel-preset-env
  • Babel v7 Plugin: https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining

Update (2017-08-01): If you want to use an official plugin, you can try the alpha build of Babel 7 with the new transform. Your mileage may vary

https://www.npmjs.com/package/babel-plugin-transform-optional-chaining

Original:

A feature that accomplishes that is currently in stage 1: Optional Chaining.

https://github.com/tc39/proposal-optional-chaining

If you want to use it today, there is a Babel plugin that accomplishes that.

https://github.com/davidyaha/ecmascript-optionals-proposal

like image 68
basicdays Avatar answered Sep 23 '22 15:09

basicdays