Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Toán tử nullish coalescing (??) trong JavaScript

Khái niệm

?? (nullish coalescing) trả về toán hạng phải chỉ khi toán hạng trái là null hoặc undefined. Khác với || coi mọi giá trị falsy (0, "", false) là "rỗng".

So sánh || vs ??

Biểu thức|| (OR)?? (Nullish)
null ?? "default""default""default"
undefined ?? "default""default""default"
0 ?? "default""default"0
"" ?? "default""default"""
false ?? "default""default"false
"hello" ?? "default""hello""hello"

Ví dụ thực tế

function config(options) {
  var timeout = options.timeout ?? 5000;     // giữ 0 nếu set timeout=0
  var retries = options.retries ?? 3;
  var debug = options.debug ?? false;        // giữ false
  // ...
}

Kết hợp với optional chaining (?. )

var city = user?.address?.city ?? "Unknown";
// an toàn: user/address có thể null/undefined

Hỗ trợ trình duyệt

ES2020. Hiện đại (Chrome 80+, Firefox 74+, Safari 13.1+, Edge 80+). Cần transpile cho IE.