Home Web Front-end JS Tutorial Nullish Coalescing Operator `??` in JavaScript

Nullish Coalescing Operator `??` in JavaScript

Sep 19, 2024 pm 04:31 PM

Nullish Coalescing Operator `??` in JavaScript

In this blog, we'll explore the nullish coalescing operator ?? in JavaScript. We'll compare it with the logical OR operator ||, discuss its precedence, and provide practical examples to help you understand its usage. Let's dive in!

Nullish Coalescing Operator ??

The nullish coalescing operator ?? is used to provide a default value when dealing with null or undefined. It returns the right-hand operand when the left-hand operand is null or undefined. Otherwise, it returns the left-hand operand.

Syntax:

result = value1 ?? value2;

Copy after login

Example:

let user = null;
let defaultUser = "Guest";

let currentUser = user ?? defaultUser;
console.log(currentUser); // Output: "Guest"

Copy after login

Explanation:

  • user is null.
  • The ?? operator returns defaultUser because user is null.

Comparison with ||

The logical OR operator || returns the first truthy value it encounters. This means it will return the right-hand operand if the left-hand operand is falsy (false, 0, "", null, undefined, NaN).

Example:

let user = "";
let defaultUser = "Guest";

let currentUser = user || defaultUser;
console.log(currentUser); // Output: "Guest"

Copy after login

Explanation:

  • user is an empty string "" (falsy).
  • The || operator returns defaultUser because user is falsy.

Key Differences

  • ??: Only considers null and undefined as falsy values.
  • ||: Considers all falsy values (false0""nullundefinedNaN).

Example:

let user = 0;
let defaultUser = "Guest";

let currentUser1 = user ?? defaultUser;
let currentUser2 = user || defaultUser;

console.log(currentUser1); // Output: 0
console.log(currentUser2); // Output: "Guest"

Copy after login

Explanation:

  • user is 0 (falsy for || but not for ??).
  • The ?? operator returns 0 because user is not null or undefined.
  • The || operator returns "Guest" because user is falsy.

Precedence

The nullish coalescing operator ?? has a lower precedence than most other operators, including the logical OR operator ||. This means that expressions involving ?? are evaluated after expressions involving ||.

Example:

let a = null;
let b = false;
let c = "Hello";

let result1 = a ?? b || c;
let result2 = a || b ?? c;

console.log(result1); // Output: "Hello"
console.log(result2); // Output: "Hello"

Copy after login

Explanation:

  • a ?? b returns false because a is null and b is false.
  • false || c returns "Hello" because false is falsy and c is truthy.
  • a || b returns false because a is null and b is false.
  • false ?? c returns "Hello" because false is not null or undefined.

Practical Examples

Let's put everything together with some practical examples:

Using ?? for Default Values

function getUserName(user) {
  return user.name ?? "Guest";
}

let user1 = { name: "Alice" };
let user2 = { age: 25 };

console.log(getUserName(user1)); // Output: "Alice"
console.log(getUserName(user2)); // Output: "Guest"

Copy after login

Explanation:

  • If user.name is null or undefined, the ?? operator returns "Guest".

Using || for Default Values

function getUserName(user) {
  return user.name || "Guest";
}

let user1 = { name: "" };
let user2 = { age: 25 };

console.log(getUserName(user1)); // Output: "Guest"
console.log(getUserName(user2)); // Output: "Guest"

Copy after login

Explanation:

  • If user.name is falsy (e.g., ""), the || operator returns "Guest".

Summary

  • ?? (Nullish Coalescing Operator): Returns the right-hand operand if the left-hand operand is null or undefined.
  • || (Logical OR Operator): Returns the first truthy value it encounters.
  • Precedence: The ?? operator has a lower precedence than the || operator.

Conclusion

The nullish coalescing operator ?? is a powerful tool in JavaScript for providing default values when dealing with null or undefined. By understanding its differences from the logical OR operator || and its precedence, you'll be able to write more robust and error-free code. Keep practicing and exploring to deepen your understanding of the nullish coalescing operator in JavaScript.

Stay tuned for more in-depth blogs on JavaScript! Happy coding!

The above is the detailed content of Nullish Coalescing Operator `??` in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

Replace String Characters in JavaScript

jQuery Check if Date is Valid jQuery Check if Date is Valid Mar 01, 2025 am 08:51 AM

jQuery Check if Date is Valid

jQuery get element padding/margin jQuery get element padding/margin Mar 01, 2025 am 08:53 AM

jQuery get element padding/margin

10 jQuery Accordions Tabs 10 jQuery Accordions Tabs Mar 01, 2025 am 01:34 AM

10 jQuery Accordions Tabs

10 Worth Checking Out jQuery Plugins 10 Worth Checking Out jQuery Plugins Mar 01, 2025 am 01:29 AM

10 Worth Checking Out jQuery Plugins

HTTP Debugging with Node and http-console HTTP Debugging with Node and http-console Mar 01, 2025 am 01:37 AM

HTTP Debugging with Node and http-console

jquery add scrollbar to div jquery add scrollbar to div Mar 01, 2025 am 01:30 AM

jquery add scrollbar to div

Custom Google Search API Setup Tutorial Custom Google Search API Setup Tutorial Mar 04, 2025 am 01:06 AM

Custom Google Search API Setup Tutorial

See all articles