User Tools

Site Tools


java-script:nullish-coalescing-vs-logicar-or-vs-logical-and

This is an old revision of the document!


|| Logical OR vs ?? Nullish Coalescing vs && Logical AND

The ||, ??, and && operators are used to perform different types of logical operations.

|| (Logical OR)

The || operator returns the first truthy value it encounters or the last value if none are truthy:

const a = 0;
const b = 'hello';
const result = a || b; // 'hello'
If you want to use || to return a boolean true or false value, you can simply convert the result to a boolean. One common way to do this is by using the Boolean constructor, or by using a double NOT (!!) operator:
const a = null;
const b = 'value';
 
const result = Boolean(a || b); // returns true
 
// Or using the double NOT operator:
 
const resultWithNot = !!(a || b); // also returns true

These expressions will evaluate to true if either a or b is truthy, and false otherwise.

?? (Nullish Coalescing)

The ?? operator returns the right-hand operand when the left-hand operand is null or undefined, and the left-hand operand otherwise.
It's useful for providing default values:

const a = undefined;
const b = 'default';
const result = a ?? b; // 'default'

&& (Logical AND)

The && operator returns the first falsy value it encounters or the last value if all are truthy:

const a = 'hello';
const b = 42;
const result = a && b; // 42

Comparison

|| is generally used for providing a fallback value when dealing with falsy values (false, 0, empty strings, null, undefined, NaN).

?? is more specific than || because it only falls back for null or undefined, not for other falsy values like 0 or an empty string ''.

&& is used to ensure that multiple conditions are truthy.

Example:

const value = 0;
const fallback1 = 'fallback';
 
const result1 = value || fallback1; // 'fallback' because 0 is falsy
const result2 = value ?? fallback1; // 0 because 0 is not null or undefined
const result3 = value && fallback1; // 0 because 0 is the first value, and it's falsy
java-script/nullish-coalescing-vs-logicar-or-vs-logical-and.1691630019.txt.gz · Last modified: 2023/08/10 04:13 by odefta