java-script:nullish-coalescing-vs-logicar-or-vs-logical-and
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
java-script:nullish-coalescing-vs-logicar-or-vs-logical-and [2023/08/10 03:31] – odefta | java-script:nullish-coalescing-vs-logicar-or-vs-logical-and [2023/08/10 04:25] (current) – odefta | ||
---|---|---|---|
Line 1: | Line 1: | ||
- | ====== || (Logical OR) vs ?? (Nullish Coalescing) vs && | + | ====== || Logical OR vs ?? Nullish Coalescing vs && Logical AND ====== |
The **||, ??, and && | The **||, ??, and && | ||
Line 11: | Line 11: | ||
const result = a || b; // ' | const result = a || b; // ' | ||
</ | </ | ||
+ | |||
+ | < | ||
+ | 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, | ||
+ | <code javascript> | ||
+ | const a = null; // falsy | ||
+ | const b = ' | ||
+ | |||
+ | 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) ===== | ===== ?? (Nullish Coalescing) ===== | ||
Line 30: | Line 45: | ||
const result = a && 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: | ||
+ | <code javascript> | ||
+ | const a = ' | ||
+ | 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: | ||
+ | <code javascript> | ||
+ | const value1 = ' | ||
+ | const value2 = 0; // falsy | ||
+ | |||
+ | const result1 = Boolean(value1 && value2); // false | ||
+ | const result2 = Boolean(value1) && Boolean(value2); | ||
+ | </ | ||
+ | </ | ||
===== Comparison ===== | ===== Comparison ===== | ||
Line 48: | Line 85: | ||
const result3 = value && fallback1; // 0 because 0 is the first value, and it's falsy | const result3 = value && fallback1; // 0 because 0 is the first value, and it's falsy | ||
</ | </ | ||
+ | |||
+ | <note tip> | ||
+ | See also [[java-script: | ||
+ | </ |
java-script/nullish-coalescing-vs-logicar-or-vs-logical-and.1691627507.txt.gz · Last modified: 2023/08/10 03:31 by odefta