proposal-nullish-coalescing

Nullish coalescing proposal x ?? y

  • 所有者: tc39/proposal-nullish-coalescing
  • 平台:
  • 許可證:
  • 分類:
  • 主題:
  • 喜歡:
    0
      比較:

Github星跟蹤圖

Nullish Coalescing for JavaScript

Status

Current Stage:

  • Stage 4

Authors

Overview and motivation

When performing property accesses, it is often desired to provide a default value if the result of that property access is null or undefined. At present, a typical way to express this intent in JavaScript is by using the , operator.

const response = {
  settings: {
    nullValue: null,
    height: 400,
    animationDuration: 0,
    headerText: '',
    showSplashScreen: false
  }
};

const undefinedValue = response.settings.undefinedValue, 'some other default'; // result: 'some other default'
const nullValue = response.settings.nullValue, 'some other default'; // result: 'some other default'

This works well for the common case of null and undefined values, but there are a number of falsy values that might produce surprising results:

const headerText = response.settings.headerText, 'Hello, world!'; // Potentially unintended. '' is falsy, result: 'Hello, world!'
const animationDuration = response.settings.animationDuration, 300; // Potentially unintended. 0 is falsy, result: 300
const showSplashScreen = response.settings.showSplashScreen, true; // Potentially unintended. false is falsy, result: true

The nullary coalescing operator is intended to handle these cases better and serves as an equality check against nullary values (null or undefined).

Syntax

Base case. If the expression at the left-hand side of the ?? operator evaluates to undefined or null, its right-hand side is returned.

const response = {
  settings: {
    nullValue: null,
    height: 400,
    animationDuration: 0,
    headerText: '',
    showSplashScreen: false
  }
};

const undefinedValue = response.settings.undefinedValue ?? 'some other default'; // result: 'some other default'
const nullValue = response.settings.nullValue ?? 'some other default'; // result: 'some other default'
const headerText = response.settings.headerText ?? 'Hello, world!'; // result: ''
const animationDuration = response.settings.animationDuration ?? 300; // result: 0
const showSplashScreen = response.settings.showSplashScreen ?? true; // result: false

Notes

While this proposal specifically calls out null and undefined values, the intent is to provide a complementary operator to the optional chaining operator. This proposal will update to match the semantics of that operator.

Prior Art

Specification

References

Prior discussion

主要指標

概覽
名稱與所有者tc39/proposal-nullish-coalescing
主編程語言HTML
編程語言HTML (語言數: 2)
平台
許可證
所有者活动
創建於2017-07-20 16:05:24
推送於2023-01-28 20:48:22
最后一次提交
發布數0
用户参与
星數1.2k
關注者數72
派生數23
提交數60
已啟用問題?
問題數41
打開的問題數0
拉請求數20
打開的拉請求數0
關閉的拉請求數6
项目设置
已啟用Wiki?
已存檔?
是復刻?
已鎖定?
是鏡像?
是私有?