DEV Community

Juan Castillo
Juan Castillo

Posted on

Understanding JavaScript's ?? (Nullish Coalescing) and || (Logical OR) Operators 🤔💡

Introduction

In JavaScript, the ?? (nullish coalescing) and || (logical OR) operators are commonly used to provide default values when a variable is "falsy" or null/undefined. Although they might seem similar, there's a key difference in how they determine when to provide the default value. Let's dive into each operator and explore their differences with some examples! 🛠️📚

The ?? (Nullish Coalescing) Operator

The ?? operator returns the right-hand side value only if the left-hand side value is null or undefined. This is particularly useful when you want to provide a default value specifically when a variable is null or undefined.

let a = null;
let b = a ?? "default"; // "default"
Enter fullscreen mode Exit fullscreen mode

The || (Logical OR) Operator

The || operator returns the right-hand side value if the left-hand side value is "falsy". In JavaScript, "falsy" values include false, 0, "" (empty string), null, undefined, and NaN.

let a = 0;
let b = a || "default"; // "default"
Enter fullscreen mode Exit fullscreen mode

Key Differences

1. Falsy Values Considered:

|| considers false, 0, "", null, undefined, and NaNas "falsy" values.
?? considers only null and undefined as "nullish" values.

2. Common Uses:

Use ?? when you want to specifically handle null and undefined and allow other "falsy" values like 0 or "".
Use || when you want a default value for any "falsy" value.

Examples

1. Using ??:

let user = {
    name: "Alice",
    age: 0,
    country: null
};

let age = user.age ?? 18;         // 0, because 0 is not null or undefined
let country = user.country ?? "Unknown"; // "Unknown", because it is null
Enter fullscreen mode Exit fullscreen mode

2. Using ||:

let user = {
    name: "Alice",
    age: 0,
    country: null
};

let age = user.age || 18;         // 18, because 0 is "falsy"
let country = user.country || "Unknown"; // "Unknown", because it is null
Enter fullscreen mode Exit fullscreen mode

Summary

  • ??: Use this operator when you only care about null or undefined.
  • ||: Use this operator when you want to cover all "falsy" values.

Understanding when to use each of these operators will help you handle default values more precisely and avoid logical errors in your code. Happy coding! 🎉✨

Top comments (0)