└── readme.markdown /readme.markdown: -------------------------------------------------------------------------------- 1 | # Undefined Coalescing Operator 2 | 3 | This is a proposal for introducing a Undefined Coalescing [(Null Coalescing Operator in C#)](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operator) operator in [ECMAScript](https://github.com/tc39/ecma262/). 4 | 5 | ## Motivation 6 | 7 | We often provide default values using the logical or operator `||`, for convenience. 8 | 9 | ```js 10 | var name = user.name || 'Bob' 11 | var bio = user.bio || 'Nothing to see here!' 12 | ``` 13 | 14 | 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. 15 | 16 | ```js 17 | var spellWand = { 18 | remaining: 0 19 | } 20 | console.log(spellWand.remaining || 5) // <- 5 21 | ``` 22 | 23 | When the left-hand side value is `undefined`, the Undefined Coalescing Operator returns the right-hand side value. 24 | 25 | ```js 26 | var user = {} 27 | console.log(user.name ?? 'Bob') // 'Bob' 28 | ``` 29 | 30 | The Undefined Coalescing Operator returns the left-hand side value in all other cases. 31 | 32 | ```js 33 | var spellWand = { 34 | remaining: 0 35 | } 36 | console.log(spellWand.remaining ?? 5) // <- 0 37 | ``` 38 | 39 | ## Implementation 40 | 41 | `left ?? right` is equivalent to `left === undefined ? right : left`. 42 | 43 | ## Limitations 44 | 45 | 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. 46 | 47 | 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. 48 | 49 | 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. 50 | --------------------------------------------------------------------------------