For AI agents: the complete documentation index is available at /tc39-atlas/llms.txt, the full documentation bundle is available at /tc39-atlas/llms-full.txt, and this page is available as Markdown at /tc39-atlas/proposals/stage/4/proposal-nullish-coalescing.md.
  • 简体中文
  • Nullish coalescing Operator S4

    中文标题:空值合并运算符

    提案概览
    提案速览

    本提案引入了空值合并运算符(?),在属性访问结果为 null 或 undefined 时提供默认值,避免对 0、'' 或 false 等假值产生意外行为。

    Note

    以下 README 来自上游仓库,其中的阶段或状态标注可能滞后;当前信息以提案概览为准。

    JavaScript 的空值合并

    状态

    当前阶段:

    • 第 4 阶段

    作者

    概述与动机

    在进行属性访问时,通常希望在属性访问的结果为 nullundefined 时提供默认值。目前,在 JavaScript 中表达这一意图的典型方式是使用 || 运算符。

    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'

    这对于 nullundefined 值的常见情况效果良好,但有许多假值可能会产生令人惊讶的结果:

    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

    空值合并运算符旨在更好地处理这些情况,并作为对空值(nullundefined)的相等性检查。

    语法

    基础情况。如果 ?? 运算符左侧的表达式求值为 undefinednull,则返回其右侧的表达式。

    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

    说明

    尽管本提案特别提到了 nullundefined 值,其意图是提供与可选链运算符互补的运算符。本提案将更新以匹配该运算符的语义。

    先例

    规范

    参考

    先前讨论