Back to Blognode

what the heck is this operator ?? in javascript.

Learn the key differences between JavaScript's || (logical OR) and ?? (nullish coalescing) operators. Discover use cases and examples to understand when to use each for handling default values and fallbacks in your JavaScript code. Improve your programming skills by mastering these essential operators!

node
what the heck is this operator ?? in javascript.

In JavaScript, || (logical OR) and ?? (nullish coalescing) are both used to provide a fallback value, but they work differently:

|| (Logical OR)

  • Usage: Used to check if the first value is "falsy" (e.g., false, 0, null, undefined, NaN, "").

  • Behavior: Returns the first "truthy" value or the last "falsy" value if none are truthy.

  • Example:

    const result = value1 || value2; 
    // If `value1` is "falsy" (like `null`, `0`, `""`), `value2` will be returned.

?? (Nullish Coalescing)

  • Usage: Used to check specifically if a value is null or undefined.

  • Behavior: Returns the right-hand value only if the left-hand value is null or undefined.

  • Example:

    const result = value1 ?? value2;
    // If `value1` is `null` or `undefined`, `value2` will be returned.

Key Difference

  • || checks for "falsy" values (like 0, false, "", null, undefined), whereas ?? only checks for null or undefined.

When to Use Which

  • Use || when you want to provide a default value for any "falsy" condition.

  • Use ?? when you want to differentiate between null/undefined and other "falsy" values like 0 or an empty string ("").