You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

JavaScript中?.和??运算符的作用是什么?是否有官方文档?

Hey there! Let's break down those two JavaScript operators you've encountered—they're both part of modern ECMAScript standards and are designed to simplify common code patterns while avoiding errors.


可选链运算符 (?.)

This operator solves the annoying problem of safely accessing nested object properties without having to write tedious null/undefined checks every time.

What it does:

When you use args?.propertyName, it checks if args is not null or undefined first. If it exists, it proceeds to access propertyName; if it doesn't, the whole expression returns undefined immediately—no TypeError thrown for trying to access a property on a non-existent value.

In your example:

args?.propertyName !== 'someValue'
  • If args is null or undefined, args?.propertyName becomes undefined, so the expression evaluates to undefined !== 'someValue' (which is true).
  • If args exists and has propertyName, it compares the actual value of propertyName to 'someValue' as you'd expect.

Before this operator, you'd have to write something like args && args.propertyName !== 'someValue'—which works, but gets messy with deeply nested properties (e.g., obj?.a?.b?.c vs obj && obj.a && obj.a.b && obj.a.b.c).


空值合并运算符 (??)

This operator is all about providing default values, but with a key difference from the older || operator: it only falls back to the default when the left-hand side is strictly null or undefined.

What it does:

In your example:

const value = props.someProp ?? props.defaultProp;
  • If props.someProp is null or undefined, value will be set to props.defaultProp.
  • If props.someProp is any other value (even "falsy" ones like 0, '', false, or NaN), value will keep props.someProp's value.

This is a big improvement over ||, which would replace any falsy value with the default. For example, if props.someProp is 0 (a valid value in many cases), props.someProp || props.defaultProp would pick the default, but ?? would correctly keep the 0.


Official Support

Both operators were introduced in ECMAScript 2020 (ES11) and are fully supported in all modern browsers, Node.js 14+, and popular JS runtimes. They're part of the official ECMAScript standard, so you can rely on them in production code (just make sure to transpile if you need to support very old environments).

内容的提问来源于stack exchange,提问作者Sai Teja Talasila

火山引擎 最新活动