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
argsisnullorundefined,args?.propertyNamebecomesundefined, so the expression evaluates toundefined !== 'someValue'(which istrue). - If
argsexists and haspropertyName, it compares the actual value ofpropertyNameto'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.somePropisnullorundefined,valuewill be set toprops.defaultProp. - If
props.somePropis any other value (even "falsy" ones like0,'',false, orNaN),valuewill keepprops.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




