[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing [Back]  [Original]

?? - JavaScript | MDN

MDN Web Docs

View in English Always switch to English

??

20207

?? null undefined

const foo = null ?? "default string";
console.log(foo);
// Expected output: "default string"

const baz = 0 ?? 42;
console.log(baz);
// Expected output: 0

js
leftExpr ?? rightExpr

|| null undefined || foo '' 0

||

?? &&||

js
null || undefined ?? "foo"; //  SyntaxError
true && undefined ?? "foo"; //  SyntaxError

js
(null || undefined) ?? "foo"; // foo

null undefined

js
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

||

js
let foo;

// foo 
let someDummyText = foo || "Hello!";

|| 0''NaNfalse 0'' NaN

js
const count = 0;
const text = "";

const qty = count || 42;
const message = text || "hi!";
console.log(qty); // 42 0
console.log(message); // "hi!" ""

null undefined

js
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

js
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

js
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