Any difference between x || [] and x ?? [] in javascript? - javascript

I've see both x || [] and x ?? [] used for providing a fallback value if x is nullish. Are there any cases where these two give different results?

If x was a non-nullish falsey value, it would be different.
x = 0;
x = x ?? []
console.log(x);
y = null;
y = y ?? []
console.log(y);

These expressions x || [] and x ?? [] are logical assignments in Javascript.
x ?? [] is used to represent null or undefined cases while x || [] represent true if either a or b is true.
x ?? [] works by evaluating if the left side of the expression is null or undefined.
x || [] works by evaluating if a or b is true. If a is true continue in the if statement. If b is true, continue in the if statement.

They do different things.
?? is called Nullish coalescing operator https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
And works checking if the left side of the evaluation is null or undefined and if it's not the case will assign the right side of the evaluation.
The previous is really useful when you are checking a variable with the value zero which will be false if you are checking for it.
|| is the Logical Operator https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR
The logical operator works as any other logical operator. Will evaluate the left side and then the right side
null || 1 // output 1
undefined || 1 // output 1
0 || 1 // 1 <-- there are cases where you want to treat zero as a truthy value and **that's where the nullish operator is handy**

Related

Javascript syntax

Can anyone explain the meaning of the assign operator? What does it mean?
It came out as true but I'm unclear on how we reached to there.
Thanks!
var x = 0 !=1;
An assignment operator assigns a value to its left operand based on the value of its right operand. In this case true will be assigned to the variable x as 1!=0 (1 not equal-to 0) is true.
Order of operations (var x = (0 != 1))
Imagine you computed just 0 != 1. This is evidently a true statement, so this would evaluate to true. If you set x to the evaluation of 0 != 1, then you receive var x = true.

Assign value to variable - Simplify existing code [duplicate]

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?
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"
function coalesce() {
var len = arguments.length;
for (var i=0; i<len; i++) {
if (arguments[i] !== null && arguments[i] !== undefined) {
return arguments[i];
}
}
return null;
}
var xyz = {};
xyz.val = coalesce(null, undefined, xyz.val, 5);
// xyz.val now contains 5
this solution works like the SQL coalesce function, it accepts any number of arguments, and returns null if none of them have a value. It behaves like the C# ?? operator in the sense that "", false, and 0 are considered NOT NULL and therefore count as actual values. If you come from a .net background, this will be the most natural feeling solution.
Yes, it is coming soon. See proposal here and implementation status here.
It looks like this:
x ?? y
Example
const response = {
settings: {
nullValue: null,
height: 400,
animationDuration: 0,
headerText: '',
showSplashScreen: false
}
};
const undefinedValue = response.settings?.undefinedValue ?? 'some other default'; // result: 'some other default'
const nullValue = response.settings?.nullValue ?? 'some other default'; // result: 'some other default'
const headerText = response.settings?.headerText ?? 'Hello, world!'; // result: ''
const animationDuration = response.settings?.animationDuration ?? 300; // result: 0
const showSplashScreen = response.settings?.showSplashScreen ?? true; // result: false
If || as a replacement of C#'s ?? isn't good enough in your case, because it swallows empty strings and zeros, you can always write your own function:
function $N(value, ifnull) {
if (value === null || value === undefined)
return ifnull;
return value;
}
var whatIWant = $N(someString, 'Cookies!');
Nobody has mentioned in here the potential for NaN, which--to me--is also a null-ish value. So, I thought I'd add my two-cents.
For the given code:
var a,
b = null,
c = parseInt('Not a number'),
d = 0,
e = '',
f = 1
;
If you were to use the || operator, you get the first non-false value:
var result = a || b || c || d || e || f; // result === 1
If you use the new ?? (null coalescing) operator, you will get c, which has the value: NaN
vas result = a ?? b ?? c ?? d ?? e ?? f; // result === NaN
Neither of these seem right to me. In my own little world of coalesce logic, which may differ from your world, I consider undefined, null, and NaN as all being "null-ish". So, I would expect to get back d (zero) from the coalesce method.
If anyone's brain works like mine, and you want to exclude NaN, then this custom coalesce method (unlike the one posted here) will accomplish that:
function coalesce() {
var i, undefined, arg;
for( i=0; i < arguments.length; i++ ) {
arg = arguments[i];
if( arg !== null && arg !== undefined
&& (typeof arg !== 'number' || arg.toString() !== 'NaN') ) {
return arg;
}
}
return null;
}
For those who want the code as short as possible, and don't mind a little lack of clarity, you can also use this as suggested by #impinball. This takes advantage of the fact that NaN is never equal to NaN. You can read up more on that here: Why is NaN not equal to NaN?
function coalesce() {
var i, arg;
for( i=0; i < arguments.length; i++ ) {
arg = arguments[i];
if( arg != null && arg === arg ) { //arg === arg is false for NaN
return arg;
}
}
return null;
}
Logical nullish assignment, 2020+ solution
A new operator is currently being added to the browsers, ??=. This combines the null coalescing operator ?? with the assignment operator =.
NOTE: This is not common in public browser versions yet. Will update as availability changes.
??= checks if the variable is undefined or null, short-circuiting if already defined. If not, the right-side value is assigned to the variable.
Basic Examples
let a // undefined
let b = null
let c = false
a ??= true // true
b ??= true // true
c ??= true // false
Object/Array Examples
let x = ["foo"]
let y = { foo: "fizz" }
x[0] ??= "bar" // "foo"
x[1] ??= "bar" // "bar"
y.foo ??= "buzz" // "fizz"
y.bar ??= "buzz" // "buzz"
x // Array [ "foo", "bar" ]
y // Object { foo: "fizz", bar: "buzz" }
Browser Support Jan '22 - 89%
Mozilla Documentation
Yes, and its proposal is Stage 4 now. This means that the proposal is ready for inclusion in the formal ECMAScript standard. You can already use it in recent desktop versions of Chrome, Edge and Firefox, but we will have to wait for a bit longer until this feature reaches cross-browser stability.
Have a look at the following example to demonstrate its behavior:
// note: this will work only if you're running latest versions of aforementioned browsers
const var1 = undefined;
const var2 = "fallback value";
const result = var1 ?? var2;
console.log(`Nullish coalescing results in: ${result}`);
Previous example is equivalent to:
const var1 = undefined;
const var2 = "fallback value";
const result = (var1 !== null && var1 !== undefined) ?
var1 :
var2;
console.log(`Nullish coalescing results in: ${result}`);
Note that nullish coalescing will not threat falsy values the way the || operator did (it only checks for undefined or null values), hence the following snippet will act as follows:
// note: this will work only if you're running latest versions of aforementioned browsers
const var1 = ""; // empty string
const var2 = "fallback value";
const result = var1 ?? var2;
console.log(`Nullish coalescing results in: ${result}`);
For TypesScript users, starting off TypeScript 3.7, this feature is also available now.
?? vs || vs &&
None of the other answers compares all three of these. Since Justin Johnson's comment has so many votes, and since double question mark vs && in javascript was marked a duplicate of this one, it makes sense to include && in an answer.
First in words, inspired by Justin Johnson's comment:
|| returns the first "truey" value, else the last value whatever it is.
&& returns the first "falsey" value, else the last value whatever it is.
?? returns the first non-null, non-undefined value, else the last value, whatever it is.
Then, demonstrated in live code:
let F1,
F2 = null,
F3 = 0,
F4 = '',
F5 = parseInt('Not a number (NaN)'),
T1 = 3,
T2 = 8
console.log( F1 || F2 || F3 || F4 || F5 || T1 || T2 ) // 3 (T1)
console.log( F1 || F2 || F3 || F4 || F5 ) // NaN (F5)
console.log( T1 && T2 && F1 && F2 && F3 && F4 && F5 ) // undefined (F1)
console.log( T1 && T2 ) // 8 (T2)
console.log( F1 ?? F2 ?? F3 ?? F4 ?? F5 ?? T1 ) // 0 (F3)
console.log( F1 ?? F2) // null (F2)
After reading your clarification, #Ates Goral's answer provides how to perform the same operation you're doing in C# in JavaScript.
#Gumbo's answer provides the best way to check for null; however, it's important to note the difference in == versus === in JavaScript especially when it comes to issues of checking for undefined and/or null.
There's a really good article about the difference in two terms here. Basically, understand that if you use == instead of ===, JavaScript will try to coalesce the values you're comparing and return what the result of the comparison after this coalescence.
beware of the JavaScript specific definition of null. there are two definitions for "no value" in javascript.
1. Null: when a variable is null, it means it contains no data in it, but the variable is already defined in the code. like this:
var myEmptyValue = 1;
myEmptyValue = null;
if ( myEmptyValue === null ) { window.alert('it is null'); }
// alerts
in such case, the type of your variable is actually Object. test it.
window.alert(typeof myEmptyValue); // prints Object
Undefined: when a variable has not been defined before in the code, and as expected, it does not contain any value. like this:
if ( myUndefinedValue === undefined ) { window.alert('it is undefined'); }
// alerts
if such case, the type of your variable is 'undefined'.
notice that if you use the type-converting comparison operator (==), JavaScript will act equally for both of these empty-values. to distinguish between them, always use the type-strict comparison operator (===).
Note that React's create-react-app tool-chain supports the null-coalescing since version 3.3.0 (released 5.12.2019). From the release notes:
Optional Chaining and Nullish Coalescing Operators
We now support the optional chaining and nullish coalescing operators!
// Optional chaining
a?.(); // undefined if `a` is null/undefined
b?.c; // undefined if `b` is null/undefined
// Nullish coalescing
undefined ?? 'some other default'; // result: 'some other default'
null ?? 'some other default'; // result: 'some other default'
'' ?? 'some other default'; // result: ''
0 ?? 300; // result: 0
false ?? true; // result: false
This said, in case you use create-react-app 3.3.0+ you can start using the null-coalesce operator already today in your React apps.
There are two items here:
Logical OR
const foo = '' || 'default string';
console.log(foo); // output is 'default string'
Nullish coalescing operator
const foo = '' ?? 'default string';
console.log(foo); // output is empty string i.e. ''
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.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
It will hopefully be available soon in Javascript, as it is in proposal phase as of Apr, 2020. You can monitor the status here for compatibility and support - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
For people using Typescript, you can use the nullish coalescing operator from Typescript 3.7
From the docs -
You can think of this feature - the ?? operator - as a way to “fall
back” to a default value when dealing with null or undefined. When we
write code like
let x = foo ?? bar();
this is a new way to say that the value foo will be used when it’s “present”; but when it’s null or undefined,
calculate bar() in its place.
Need to support old browser and have a object hierarchy
body.head.eyes[0] //body, head, eyes may be null
may use this,
(((body||{}) .head||{}) .eyes||[])[0] ||'left eye'
ECMAScript 2021 enabled two new features:
Nullish coalescing operator (??) which is a logical operator that returns its right-hand side operand when its left-hand side operand is either null or undefined, and otherwise returns its left-hand side operand.
let b = undefined ?? 5;
console.log(b); // 5
Logical nullish assignment (x ??= y) operator which only assigns if x has a nullish value (null or undefined).
const car = {speed : 20};
car.speed ??= 5;
console.log(car.speed);
car.name ??= "reno";
console.log(car.name);
More about Logical nullish assignment can be found here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_nullish_assignment
More about Nullish coalescing operator can be found here
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
Now it has full support in latest version of major browsers like Chrome, Edge, Firefox , Safari etc. Here's the comparison between the null operator and Nullish Coalescing Operator
const response = {
settings: {
nullValue: null,
height: 400,
animationDuration: 0,
headerText: '',
showSplashScreen: false
}
};
/* OR Operator */
const undefinedValue = response.settings.undefinedValue || 'Default Value'; // 'Default Value'
const nullValue = response.settings.nullValue || 'Default Value'; // 'Default Value'
const headerText = response.settings.headerText || 'Hello, world!'; // 'Hello, world!'
const animationDuration = response.settings.animationDuration || 300; // 300
const showSplashScreen = response.settings.showSplashScreen || true; // true
/* Nullish Coalescing Operator */
const undefinedValue = response.settings.undefinedValue ?? 'Default Value'; // 'Default Value'
const nullValue = response.settings.nullValue ?? ''Default Value'; // 'Default Value'
const headerText = response.settings.headerText ?? 'Hello, world!'; // ''
const animationDuration = response.settings.animationDuration ?? 300; // 0
const showSplashScreen = response.settings.showSplashScreen ?? true; // false
Those who are using Babel, need to upgrade to the latest version to use nullish coalescing (??):
Babel 7.8.0 supports the new ECMAScript 2020 features by default: you
don't need to enable individual plugins for nullish coalescing (??),
optional chaining (?.) and dynamic import() anymore with preset-env
From https://babeljs.io/blog/2020/01/11/7.8.0
Chain multiple values / several values
"short circuit" is enabled: do not evaluate any further if one of the first values is valid
that means order matters, the most left values are prioritized
const value = first ?? second ?? third ?? "default";
I was trying to check if an input is null and then use the value accordingly. This is my code.
let valueToBeConsidered = !inputValue ? "trueCondition" : "falseCondition",
So if inputValue is null then valueToBeConsidered = falseCondition and if inputValue has a value then valueToBeConsidered = trueCondition

Binary conditional operator with assignment [duplicate]

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?
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"
function coalesce() {
var len = arguments.length;
for (var i=0; i<len; i++) {
if (arguments[i] !== null && arguments[i] !== undefined) {
return arguments[i];
}
}
return null;
}
var xyz = {};
xyz.val = coalesce(null, undefined, xyz.val, 5);
// xyz.val now contains 5
this solution works like the SQL coalesce function, it accepts any number of arguments, and returns null if none of them have a value. It behaves like the C# ?? operator in the sense that "", false, and 0 are considered NOT NULL and therefore count as actual values. If you come from a .net background, this will be the most natural feeling solution.
Yes, it is coming soon. See proposal here and implementation status here.
It looks like this:
x ?? y
Example
const response = {
settings: {
nullValue: null,
height: 400,
animationDuration: 0,
headerText: '',
showSplashScreen: false
}
};
const undefinedValue = response.settings?.undefinedValue ?? 'some other default'; // result: 'some other default'
const nullValue = response.settings?.nullValue ?? 'some other default'; // result: 'some other default'
const headerText = response.settings?.headerText ?? 'Hello, world!'; // result: ''
const animationDuration = response.settings?.animationDuration ?? 300; // result: 0
const showSplashScreen = response.settings?.showSplashScreen ?? true; // result: false
If || as a replacement of C#'s ?? isn't good enough in your case, because it swallows empty strings and zeros, you can always write your own function:
function $N(value, ifnull) {
if (value === null || value === undefined)
return ifnull;
return value;
}
var whatIWant = $N(someString, 'Cookies!');
Nobody has mentioned in here the potential for NaN, which--to me--is also a null-ish value. So, I thought I'd add my two-cents.
For the given code:
var a,
b = null,
c = parseInt('Not a number'),
d = 0,
e = '',
f = 1
;
If you were to use the || operator, you get the first non-false value:
var result = a || b || c || d || e || f; // result === 1
If you use the new ?? (null coalescing) operator, you will get c, which has the value: NaN
vas result = a ?? b ?? c ?? d ?? e ?? f; // result === NaN
Neither of these seem right to me. In my own little world of coalesce logic, which may differ from your world, I consider undefined, null, and NaN as all being "null-ish". So, I would expect to get back d (zero) from the coalesce method.
If anyone's brain works like mine, and you want to exclude NaN, then this custom coalesce method (unlike the one posted here) will accomplish that:
function coalesce() {
var i, undefined, arg;
for( i=0; i < arguments.length; i++ ) {
arg = arguments[i];
if( arg !== null && arg !== undefined
&& (typeof arg !== 'number' || arg.toString() !== 'NaN') ) {
return arg;
}
}
return null;
}
For those who want the code as short as possible, and don't mind a little lack of clarity, you can also use this as suggested by #impinball. This takes advantage of the fact that NaN is never equal to NaN. You can read up more on that here: Why is NaN not equal to NaN?
function coalesce() {
var i, arg;
for( i=0; i < arguments.length; i++ ) {
arg = arguments[i];
if( arg != null && arg === arg ) { //arg === arg is false for NaN
return arg;
}
}
return null;
}
Logical nullish assignment, 2020+ solution
A new operator is currently being added to the browsers, ??=. This combines the null coalescing operator ?? with the assignment operator =.
NOTE: This is not common in public browser versions yet. Will update as availability changes.
??= checks if the variable is undefined or null, short-circuiting if already defined. If not, the right-side value is assigned to the variable.
Basic Examples
let a // undefined
let b = null
let c = false
a ??= true // true
b ??= true // true
c ??= true // false
Object/Array Examples
let x = ["foo"]
let y = { foo: "fizz" }
x[0] ??= "bar" // "foo"
x[1] ??= "bar" // "bar"
y.foo ??= "buzz" // "fizz"
y.bar ??= "buzz" // "buzz"
x // Array [ "foo", "bar" ]
y // Object { foo: "fizz", bar: "buzz" }
Browser Support Jan '22 - 89%
Mozilla Documentation
Yes, and its proposal is Stage 4 now. This means that the proposal is ready for inclusion in the formal ECMAScript standard. You can already use it in recent desktop versions of Chrome, Edge and Firefox, but we will have to wait for a bit longer until this feature reaches cross-browser stability.
Have a look at the following example to demonstrate its behavior:
// note: this will work only if you're running latest versions of aforementioned browsers
const var1 = undefined;
const var2 = "fallback value";
const result = var1 ?? var2;
console.log(`Nullish coalescing results in: ${result}`);
Previous example is equivalent to:
const var1 = undefined;
const var2 = "fallback value";
const result = (var1 !== null && var1 !== undefined) ?
var1 :
var2;
console.log(`Nullish coalescing results in: ${result}`);
Note that nullish coalescing will not threat falsy values the way the || operator did (it only checks for undefined or null values), hence the following snippet will act as follows:
// note: this will work only if you're running latest versions of aforementioned browsers
const var1 = ""; // empty string
const var2 = "fallback value";
const result = var1 ?? var2;
console.log(`Nullish coalescing results in: ${result}`);
For TypesScript users, starting off TypeScript 3.7, this feature is also available now.
?? vs || vs &&
None of the other answers compares all three of these. Since Justin Johnson's comment has so many votes, and since double question mark vs && in javascript was marked a duplicate of this one, it makes sense to include && in an answer.
First in words, inspired by Justin Johnson's comment:
|| returns the first "truey" value, else the last value whatever it is.
&& returns the first "falsey" value, else the last value whatever it is.
?? returns the first non-null, non-undefined value, else the last value, whatever it is.
Then, demonstrated in live code:
let F1,
F2 = null,
F3 = 0,
F4 = '',
F5 = parseInt('Not a number (NaN)'),
T1 = 3,
T2 = 8
console.log( F1 || F2 || F3 || F4 || F5 || T1 || T2 ) // 3 (T1)
console.log( F1 || F2 || F3 || F4 || F5 ) // NaN (F5)
console.log( T1 && T2 && F1 && F2 && F3 && F4 && F5 ) // undefined (F1)
console.log( T1 && T2 ) // 8 (T2)
console.log( F1 ?? F2 ?? F3 ?? F4 ?? F5 ?? T1 ) // 0 (F3)
console.log( F1 ?? F2) // null (F2)
After reading your clarification, #Ates Goral's answer provides how to perform the same operation you're doing in C# in JavaScript.
#Gumbo's answer provides the best way to check for null; however, it's important to note the difference in == versus === in JavaScript especially when it comes to issues of checking for undefined and/or null.
There's a really good article about the difference in two terms here. Basically, understand that if you use == instead of ===, JavaScript will try to coalesce the values you're comparing and return what the result of the comparison after this coalescence.
beware of the JavaScript specific definition of null. there are two definitions for "no value" in javascript.
1. Null: when a variable is null, it means it contains no data in it, but the variable is already defined in the code. like this:
var myEmptyValue = 1;
myEmptyValue = null;
if ( myEmptyValue === null ) { window.alert('it is null'); }
// alerts
in such case, the type of your variable is actually Object. test it.
window.alert(typeof myEmptyValue); // prints Object
Undefined: when a variable has not been defined before in the code, and as expected, it does not contain any value. like this:
if ( myUndefinedValue === undefined ) { window.alert('it is undefined'); }
// alerts
if such case, the type of your variable is 'undefined'.
notice that if you use the type-converting comparison operator (==), JavaScript will act equally for both of these empty-values. to distinguish between them, always use the type-strict comparison operator (===).
Note that React's create-react-app tool-chain supports the null-coalescing since version 3.3.0 (released 5.12.2019). From the release notes:
Optional Chaining and Nullish Coalescing Operators
We now support the optional chaining and nullish coalescing operators!
// Optional chaining
a?.(); // undefined if `a` is null/undefined
b?.c; // undefined if `b` is null/undefined
// Nullish coalescing
undefined ?? 'some other default'; // result: 'some other default'
null ?? 'some other default'; // result: 'some other default'
'' ?? 'some other default'; // result: ''
0 ?? 300; // result: 0
false ?? true; // result: false
This said, in case you use create-react-app 3.3.0+ you can start using the null-coalesce operator already today in your React apps.
There are two items here:
Logical OR
const foo = '' || 'default string';
console.log(foo); // output is 'default string'
Nullish coalescing operator
const foo = '' ?? 'default string';
console.log(foo); // output is empty string i.e. ''
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.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
It will hopefully be available soon in Javascript, as it is in proposal phase as of Apr, 2020. You can monitor the status here for compatibility and support - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
For people using Typescript, you can use the nullish coalescing operator from Typescript 3.7
From the docs -
You can think of this feature - the ?? operator - as a way to “fall
back” to a default value when dealing with null or undefined. When we
write code like
let x = foo ?? bar();
this is a new way to say that the value foo will be used when it’s “present”; but when it’s null or undefined,
calculate bar() in its place.
Need to support old browser and have a object hierarchy
body.head.eyes[0] //body, head, eyes may be null
may use this,
(((body||{}) .head||{}) .eyes||[])[0] ||'left eye'
ECMAScript 2021 enabled two new features:
Nullish coalescing operator (??) which is a logical operator that returns its right-hand side operand when its left-hand side operand is either null or undefined, and otherwise returns its left-hand side operand.
let b = undefined ?? 5;
console.log(b); // 5
Logical nullish assignment (x ??= y) operator which only assigns if x has a nullish value (null or undefined).
const car = {speed : 20};
car.speed ??= 5;
console.log(car.speed);
car.name ??= "reno";
console.log(car.name);
More about Logical nullish assignment can be found here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_nullish_assignment
More about Nullish coalescing operator can be found here
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
Now it has full support in latest version of major browsers like Chrome, Edge, Firefox , Safari etc. Here's the comparison between the null operator and Nullish Coalescing Operator
const response = {
settings: {
nullValue: null,
height: 400,
animationDuration: 0,
headerText: '',
showSplashScreen: false
}
};
/* OR Operator */
const undefinedValue = response.settings.undefinedValue || 'Default Value'; // 'Default Value'
const nullValue = response.settings.nullValue || 'Default Value'; // 'Default Value'
const headerText = response.settings.headerText || 'Hello, world!'; // 'Hello, world!'
const animationDuration = response.settings.animationDuration || 300; // 300
const showSplashScreen = response.settings.showSplashScreen || true; // true
/* Nullish Coalescing Operator */
const undefinedValue = response.settings.undefinedValue ?? 'Default Value'; // 'Default Value'
const nullValue = response.settings.nullValue ?? ''Default Value'; // 'Default Value'
const headerText = response.settings.headerText ?? 'Hello, world!'; // ''
const animationDuration = response.settings.animationDuration ?? 300; // 0
const showSplashScreen = response.settings.showSplashScreen ?? true; // false
Those who are using Babel, need to upgrade to the latest version to use nullish coalescing (??):
Babel 7.8.0 supports the new ECMAScript 2020 features by default: you
don't need to enable individual plugins for nullish coalescing (??),
optional chaining (?.) and dynamic import() anymore with preset-env
From https://babeljs.io/blog/2020/01/11/7.8.0
Chain multiple values / several values
"short circuit" is enabled: do not evaluate any further if one of the first values is valid
that means order matters, the most left values are prioritized
const value = first ?? second ?? third ?? "default";
I was trying to check if an input is null and then use the value accordingly. This is my code.
let valueToBeConsidered = !inputValue ? "trueCondition" : "falseCondition",
So if inputValue is null then valueToBeConsidered = falseCondition and if inputValue has a value then valueToBeConsidered = trueCondition

What does this mean?: x || x === {}

Does the following:
x || x === {}
not mean !!x, that is, x is defined?
That comparison makes no sense, because either x is truthy, then you get the result of x, or falsy, you get false (a falsy value is never strict equal to an empty object instance).
A concise version would be
x || false
for give me x or false.
x || x === {} means basically x || false.
!!x means "is x truthy", so it's not exactly the same - x || x === {} will return x if x is truthy.
In the same case, !!x will return true.
|| operator means "if left side is truthy (not null, not undefined, not 0 etc. - see All falsey values in JavaScript for details) return left side, else return right side".
On the right side you have x === {} which always evaluates to false, since strict comparison means comparing reference-wise (i.e., "is x the same object as {}, which is never true)
!!x and x || x === {} will be the same only if x === true or x === false
|| returns the left hand side if the LHS is a true value. So if x is a true value, it returns x.
Otherwise, it compares x to a new object, which will always be false, and returns that.
So if x is true, you get (an unmodified) x otherwise you get an explicit boolean false.
This is different to !!x since that would return a boolean true if x was a true value.

The interpretation of one line Javascript code

What is the interpretation of this line in Javascript.
var x[],matrix[],n;
...
n = (matrix = x) && matrix.length;
Despite I searched for it, I couldn't find any tips.
Thank you
It does this:
Assigns the value of x to matrix; the result of the matrix = x expression is the value that was assigned (this is true of all assignment expressions). Let's call that value "x-value". I don't want to call it x from here on out, because x is only evaluated once.
If x-value is truthy1 (coerces to true), it assigns matrix.length to n; otherwise, assigns x-value to n.
So for instance, if x is [], the code sets matrix to point to the same empty array x does and sets n to 0 (matrix.length after the assignment). Other examples (I'd written these before you edited your question): If x is "foo", it sets matrix to "foo" and sets n to 3 (the length of matrix). If x is "" (a falsy value), it sets matrix to "" and sets n to "". If x is {foo:"bar"}, it sets matrix to refer to that same object and sets n to undefined (since the object has no length property). You get the idea.
#2 above comes about because && is not just a simple logical AND operator. a && b works like this:
Evaluate a to get its value; let's call that a-value
If a-value is falsy, the result of the && operator is a-value
Otherwise, evaluate b and make that the result of the && operator
1 "Truthy" values are any values that aren't "falsy." The falsy values are 0, null, undefined, "", NaN, and of course, false.
We can interpret it as some pseudocode like this:
var x[],matrix[],n;
...
matrix = x
if(x is not in [null, false, 0, undefined, "NaN",""])
n = matrix.length
else
n = x
(matrix = x) is the assignment operation of x into a variable matrix. Here x is an array, hence the result of this operation gives a truthy value, and hence the later part takes place.
E.g. if
var x, matrix = [], n;
n = (matrix = x) && matrix.length;
won't work as the (matrix = x) is a falsy operation. n gets assigned undefined (because that's the value x has).

Categories