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

(??) - JavaScript | MDN

This page was translated from English by the community. Learn more and join the MDN Web Docs community.

View in English Always switch to English

(??)

Baseline Widely available

This feature is well established and works across many devices and browser versions. Its been available across browsers since 2020 ..

(??) , , null undefined, .

(||), , , null undefined. , || foo, , (, '' 0). .

|| , () .

In this article

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.

js
const nullValue = null;
const emptyText = ""; // 
const someNumber = 42;

const valA = nullValue ?? "  A";
const valB = emptyText ?? "  B";
const valC = someNumber ?? 0;

console.log(valA); // "  A"
console.log(valB); // "" (      null  undefined)
console.log(valC); // 42

, , (||):

js
let foo;

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

|| , , (0, '', NaN, null, undefined). , , 0, '', NaN.

js
let count = 0;
let text = "";

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

, , null undefined ( ):

js
let myText = ""; //   ( )

let notFalsyText = myText || ", ";
console.log(notFalsyText); // , 

let preservingFalsy = myText ?? ", ";
console.log(preservingFalsy); // '' (.. myText   undefined,  null)

, , 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), 
//    

(&&) (||) ?? . SyntaxError.

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

, , :

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

(?.)

undefined null, (?.)(/ru/docs/Web/JavaScript/Reference/Operators/Optional_chaining), , null undefined.

js
let foo = { someFooProp: "" };

console.log(foo.someFooProp?.toUpperCase() ?? " "); // ""
console.log(foo.someBarProp?.toUpperCase() ?? " "); // " "

Specification
ECMAScript 2027 LanguageSpecification
# prod-CoalesceExpression


Web Proxy Viewer  |  New URL  |  Original Page