User Tools

Site Tools


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

|| 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; // falsy
const b = 'value'; // truthy
 
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
If you want to use && operator to return a boolean true or false value, you can simply convert the result to a boolean:
const a = 'hello'; // truthy
const b = 42; // truthy
 
const result1 = Boolean(a && b); // true
const result2 = Boolean(a) && Boolean(b); // true
const result3 = !!a && !!b; //true
const result4 = !!(a && b); //true

Other example:

const value1 = 'hello'; // truthy
const value2 = 0; // falsy
 
const result1 = Boolean(value1 && value2); // false
const result2 = Boolean(value1) && Boolean(value2); // true && false = false

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.txt · Last modified: 2023/08/10 04:25 by odefta