All Projects → bevacqua → proposal-undefined-coalescing-operator

bevacqua / proposal-undefined-coalescing-operator

Licence: other
Undefined Coalescing Operator proposal for ECMAScript

Undefined Coalescing Operator

This is a proposal for introducing a Undefined Coalescing (Null Coalescing Operator in C#) operator in ECMAScript.

Motivation

We often provide default values using the logical or operator ||, for convenience.

var name = user.name || 'Bob'
var bio = user.bio || 'Nothing to see here!'

Sometimes, however, the falsy check gets in the way. Particularly for those cases where the value is '' or 0, in which case we often want to preserve those values.

var spellWand = {
  remaining: 0
}
console.log(spellWand.remaining || 5) // <- 5

When the left-hand side value is undefined, the Undefined Coalescing Operator returns the right-hand side value.

var user = {}
console.log(user.name ?? 'Bob') // 'Bob'

The Undefined Coalescing Operator returns the left-hand side value in all other cases.

var spellWand = {
  remaining: 0
}
console.log(spellWand.remaining ?? 5) // <- 0

Implementation

left ?? right is equivalent to left === undefined ? right : left.

Limitations

C# coalesces null, they however don't have a concept for undefined. In JavaScript null is often treated as interchangeable with undefined, but sometimes it's not.

Default values in JavaScript function parameters or while destructuring don't consider null to be a missing value, and thus logic and the principle of least surprise dictate the Undefined Coalescing Operator shouldn't either.

Under the current proposal, null is not covered by the Undefined Coalescing Operator, and left === null ? right : left should still be used for this case.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].