| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing | [Back] [Original] |
Get to know MDN better
const foo = null ?? "default string";
console.log(foo);
// Expected output: "default string"
const baz = 0 ?? 42;
console.log(baz);
// Expected output: 0
leftExpr ?? rightExpr
|| null undefined || foo '' 0
null || undefined ?? "foo"; // SyntaxError
true && undefined ?? "foo"; // SyntaxError
(null || undefined) ?? "foo"; // foo
null undefined
const nullValue = null;
const emptyText = ""; //
const someNumber = 42;
const valA = nullValue ?? "valA ";
const valB = emptyText ?? "valB ";
const valC = someNumber ?? 0;
console.log(valA); // "valA "
console.log(valB); // "" null undefined
console.log(valC); // 42
let foo;
// foo
let someDummyText = foo || "Hello!";
|| 0''NaNfalse 0'' NaN
const count = 0;
const text = "";
const qty = count || 42;
const message = text || "hi!";
console.log(qty); // 42 0
console.log(message); // "hi!" ""
null undefined
const myText = ""; //
const notFalsyText = myText || "Hello world";
console.log(notFalsyText); // Hello world
const preservingFalsy = myText ?? "Hi neighborhood";
console.log(preservingFalsy); // ''myText undefined null
OR AND null undefined
function A() {
console.log(" A ");
return undefined;
}
function B() {
console.log(" B ");
return false;
}
function C() {
console.log(" C ");
return "foo";
}
console.log(A() ?? C());
// " A "" C ""foo"
// A() undefined
console.log(B() ?? C());
// " B ""false"
// B() false null undefined
//
?. undefined null ?. null undefined
const foo = { someFooProp: "hi" };
console.log(foo.someFooProp?.toUpperCase() ?? "not available"); // "HI"
console.log(foo.someBarProp?.toUpperCase() ?? "not available"); // "not available"
| ECMAScript 2027 LanguageSpecification # prod-CoalesceExpression |
| Web Proxy Viewer | New URL | Original Page |