Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a "null coalescing" operator in JavaScript?

Is there a null coalescing operator in Javascript?

For example, in C#, I can do this:

String someString = null; var whatIWant = someString ?? "Cookies!"; 

The best approximation I can figure out for Javascript is using the conditional operator:

var someString = null; var whatIWant = someString ? someString : 'Cookies!'; 

Which is sorta icky IMHO. Can I do better?

like image 299
Daniel Schaffer Avatar asked Jan 24 '09 18:01

Daniel Schaffer


People also ask

When was null coalesce added to JavaScript?

JavaScript made sure this can be handled with its nullish operator also known as the Null Coalescing Operator, which was added to the language with ECMAScript 2020. With it, you can either return a value or assign it to some other value, depending on a boolean expression.

Does JavaScript have an Elvis operator?

2020 Update. JavaScript now has equivalents for both the Elvis Operator and the Safe Navigation Operator.

IS null operator in JavaScript?

The nullish coalescing operator ( ?? ) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined , and otherwise returns its left-hand side operand.

How do you write null in JavaScript?

In JavaScript, null is a special value that represents an empty or unknown value. For example, let number = null; The code above suggests that the number variable is empty at the moment and may have a value later.


1 Answers

Update

JavaScript now supports the nullish coalescing operator (??). It returns its right-hand-side operand when its left-hand-side operand is null or undefined, and otherwise returns its left-hand-side operand.

Old Answer

Please check compatibility before using it.


The JavaScript equivalent of the C# null coalescing operator (??) is using a logical OR (||):

var whatIWant = someString || "Cookies!"; 

There are cases (clarified below) that the behaviour won't match that of C#, but this is the general, terse way of assigning default/alternative values in JavaScript.


Clarification

Regardless of the type of the first operand, if casting it to a Boolean results in false, the assignment will use the second operand. Beware of all the cases below:

alert(Boolean(null)); // false alert(Boolean(undefined)); // false alert(Boolean(0)); // false alert(Boolean("")); // false alert(Boolean("false")); // true -- gotcha! :) 

This means:

var whatIWant = null || new ShinyObject(); // is a new shiny object var whatIWant = undefined || "well defined"; // is "well defined" var whatIWant = 0 || 42; // is 42 var whatIWant = "" || "a million bucks"; // is "a million bucks" var whatIWant = "false" || "no way"; // is "false" 
like image 142
5 revs, 3 users 67% Avatar answered Sep 28 '22 08:09

5 revs, 3 users 67%