User Tools

Site Tools


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

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
java-script:nullish-coalescing-vs-logicar-or-vs-logical-and [2023/08/10 03:31] odeftajava-script:nullish-coalescing-vs-logicar-or-vs-logical-and [2023/08/10 04:25] (current) odefta
Line 1: Line 1:
-====== || (Logical ORvs ?? (Nullish Coalescingvs && (Logical AND======+====== || Logical OR vs ?? Nullish Coalescing vs && Logical AND ======
  
 The **||, ??, and &&** operators are used to perform different types of logical operations. The **||, ??, and &&** operators are used to perform different types of logical operations.
Line 11: Line 11:
 const result = a || b; // 'hello' const result = a || b; // 'hello'
 </code> </code>
 +
 +<note>
 +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 [[java-script:double-not-operator|double NOT (!!) operator]]:
 +<code javascript>
 +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
 +</code>
 +These expressions will evaluate to true if either a or b is truthy, and false otherwise.
 +</note>
  
 ===== ?? (Nullish Coalescing) ===== ===== ?? (Nullish Coalescing) =====
Line 30: Line 45:
 const result = a && b; // 42 const result = a && b; // 42
 </code> </code>
 +
 +<note>
 +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 = '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
 +</code>
 +
 +Other example:
 +<code javascript>
 +const value1 = 'hello'; // truthy
 +const value2 = 0; // falsy
 +
 +const result1 = Boolean(value1 && value2); // false
 +const result2 = Boolean(value1) && Boolean(value2); // true && false = false
 +</code>
 +</note>
  
 ===== 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
 </code> </code>
 +
 +<note tip>
 +See also [[java-script:bitwise-or-bitwise-and-ternary-optional-chaining-operators|bitwise operators]].
 +</note>
java-script/nullish-coalescing-vs-logicar-or-vs-logical-and.1691627507.txt.gz · Last modified: 2023/08/10 03:31 by odefta