可选链操作符(?.)用于安全访问嵌套属性、方法或数组索引,遇 null 或 undefined 时自动短路返回 undefined,避免报错;常与空值合并操作符(??)配合提供默认值。
可选链操作符(?.)是 JavaScript 中用于安全访问嵌套对象属性的语法糖,它能在访问过程中遇到 null 或 undefined 时自动停止并返回 undefined,而不是抛出错误。
在没有可选链之前,访问类似 user.profile.address.city 这样的深层属性,必须层层检查是否为 null 或 undefined,否则一碰到中间某个值为空就会报错:Cannot read property 'address' of undefined。
用传统方式写,得这样兜底:
const city = user && user.profile && user.profile.address && user.profile.address.city;
只需在可能为空的对象后加 ?.,它会“短路”:一旦左侧求值为 null 或 undefined,整个表达式立刻返回 undefined,不再继续访问。

user?.profile?.address?.city —— 安全读取嵌套属性obj?.method?.() —— 安全调用方法(先检查方法是否存在,再调用)arr?.[index] —— 安全访问数组索引(如 list?.[0]?.name)可选链只对 null 和 undefined 短路,其他假值(如 false、0、空字符串)不会中断。
它不能替代逻辑判断,比如:
user?.name || '匿名' 是常见搭配,用于提供默认值user?.profile?.address?.toString() 如果 address 是 null,不会报错,但结果是 undefined;如果想确保调用 toString,得确认 address 存在且有该方法可选链常和 ?? 搭配,让默认值更清晰:
const city = user?.profile?.address?.city ?? '未知城市';
这里 ?. 防止报错,?? 提供兜底值,语义明确、不易出错。
基本上就这些。它不复杂,但容易忽略——尤其在处理 API 返回的不确定结构时,一个 ?. 就能省掉一堆防御性代码。