the Nullish Coalescing Operator (??) in JavaScript
What is `??`?
The `??` operator helps us decide if a value is empty or not. In JavaScript, a value is **empty** when it is `null` (nothing) or `undefined` (not defined).
The **`??`** operator looks like two question marks together: `??`. Here’s what it does:
- If the first value is NOT empty , it uses the first value.
- If the first value is empty, it uses the second value instead.
That’s like saying, “If my box isn’t empty, give me what’s in the box. If it’s empty, give me my favorite toy.”
How does it work?
Let's see it in action with some simple examples!
# Example 1: Choosing a name
let userName;
console.log(userName ?? "Anonymous"); // Output: "Anonymous"
- Here, we have a variable called `userName`, but we didn’t give it a name yet. So it’s **empty** (`undefined`).
- The `??` operator checks if `userName` is empty. Since it’s empty, it chooses `"Anonymous"` instead. 😊
### Example 2: The Name is Not Empty
let userName = "John";
console.log(userName ?? "Anonymous"); // Output: "John"
- Now we have given `userName` the name `"John"`.
- The **`??`** operator checks if `userName` is empty. This time it’s not, so it chooses `"John"`. Nice! 👍
# Example 3: Picking the First Value that Isn’t Empty
Imagine you have three boxes, and you want to pick something from the first box that isn’t empty:
let firstName = null;
let lastName = null;
let nickName = "SuperCoder";
console.log(firstName ?? lastName ?? nickName ?? "Anonymous"); // Output: "SuperCoder"
- Here, both `firstName` and `lastName` are empty (`null`), but `nickName` has `"SuperCoder"`.
- The **`??`** operator picks `"SuperCoder"` because it’s the first value that isn’t empty.
5
7 comments
Emmanuel Kouadio
6
the Nullish Coalescing Operator (??) in JavaScript
University of Code
skool.com/universityofcode
You'll get Exclusive Lessons & Content, Badass Community Support & More here to elevate as a Dev!
Leaderboard (30-day)
powered by