Javascript nullish coalescing operator
Created By: chatGPT
The nullish coalescing operator (??) is a logical operator in JavaScript that allows you to provide a fallback value when dealing with
null
or undefined
. This is particularly useful to ensure that your variables have meaningful values without having to repeatedly check for these falsy values.const value = someVariable ?? 'default';
In the example above, if
someVariable
is either null
or undefined
, value
will be set to 'default'
. Otherwise, it will take the value of someVariable
.const userInput = null;
const fallback = 'Default Value';
const result = userInput ?? fallback;
console.log(result); // Output: 'Default Value'
It's important to note that the nullish coalescing operator only checks for
null
and undefined
, not for other falsy values like 0
, false
, NaN
, or an empty string (''
). This means that if your variable holds a falsy value but is not null
or undefined
, it will still be returned.const input = 0;
const defaultValue = 10;
const finalValue = input ?? defaultValue;
console.log(finalValue); // Output: 0