Home > Web Front-end > JS Tutorial > Unlocking JavaScript: Logical OR (||) vs Nullish Coalescing Operator (??)

Unlocking JavaScript: Logical OR (||) vs Nullish Coalescing Operator (??)

王林
Release: 2024-07-28 09:23:43
Original
1077 people have browsed it

Unlocking JavaScript: Logical OR (||) vs Nullish Coalescing Operator (??)

Introduction

JavaScript, being one of the most popular programming languages, provides developers with a range of operators to handle various logical operations. Among these, the Logical OR (||) and the Nullish Coalescing (??) operators are fundamental tools for managing default values and handling nullish values. This article will delve into the differences between these two operators, their use cases, and practical, complex examples to illustrate their usage.

Understanding Logical OR (||) Operator

The Logical OR (||) operator in JavaScript is widely used to return the first truthy value among its operands or the last value if none are truthy. It is primarily used for setting default values.

Syntax

result = operand1 || operand2;
Copy after login

How it Works

The || operator evaluates from left to right, returning the first operand if it is truthy; otherwise, it evaluates and returns the second operand.

Example 1: Setting Default Values

let userInput = '';
let defaultText = 'Hello, World!';

let message = userInput || defaultText;
console.log(message); // Output: 'Hello, World!'
Copy after login

In this example, userInput is an empty string (falsy), so defaultText is returned.

Example 2: Handling Multiple Values

let firstName = null;
let lastName = 'Doe';

let name = firstName || lastName || 'Anonymous';
console.log(name); // Output: 'Doe'
Copy after login

Here, firstName is null (falsy), so lastName is returned as it is truthy.

Limitations of Logical OR (||) Operator

The main limitation of the || operator is that it treats several values as falsy, such as 0, NaN, '', false, null, and undefined. This can lead to unexpected results when these values are intended to be valid.

Introducing Nullish Coalescing (??) Operator

The Nullish Coalescing (??) operator is a more recent addition to JavaScript, introduced in ES2020. It is designed to handle cases where null or undefined are explicitly meant to be the only nullish values considered.

Syntax

result = operand1 ?? operand2;
Copy after login

How it Works

The ?? operator returns the right-hand operand when the left-hand operand is null or undefined. Otherwise, it returns the left-hand operand.

Example 1: Setting Default Values

let userInput = '';
let defaultText = 'Hello, World!';

let message = userInput ?? defaultText;
console.log(message); // Output: ''
Copy after login

In this example, userInput is an empty string, which is not null or undefined, so it is returned.

Example 2: Handling Nullish Values

let firstName = null;
let lastName = 'Doe';

let name = firstName ?? lastName ?? 'Anonymous';
console.log(name); // Output: 'Doe'
Copy after login

Here, firstName is null, so lastName is returned as it is neither null nor undefined.

Comparing Logical OR (||) and Nullish Coalescing (??) Operators

Example 1: Comparing Falsy Values

let value1 = 0;
let value2 = '';

let resultOR = value1 || 'default';
let resultNullish = value1 ?? 'default';

console.log(resultOR); // Output: 'default'
console.log(resultNullish); // Output: 0
Copy after login

In this example, 0 is considered falsy by the || operator but is a valid value for the ?? operator.

Example 2: Using Both Operators Together

let userInput = null;
let fallbackText = 'Default Text';

let message = (userInput ?? fallbackText) || 'Fallback Message';
console.log(message); // Output: 'Default Text'
Copy after login

Here, userInput is null, so fallbackText is used by the ?? operator. Then the result is checked by the || operator, but since fallbackText is truthy, it is returned.

Complex Examples of Logical OR (||) and Nullish Coalescing (??) Operators

Example 3: Nested Operations with Objects

Consider a scenario where you need to set default values for nested object properties.

let userSettings = {
  theme: {
    color: '',
    font: null
  }
};

let defaultSettings = {
  theme: {
    color: 'blue',
    font: 'Arial'
  }
};

let themeColor = userSettings.theme.color || defaultSettings.theme.color;
let themeFont = userSettings.theme.font ?? defaultSettings.theme.font;

console.log(themeColor); // Output: 'blue'
console.log(themeFont); // Output: 'Arial'
Copy after login

In this example, userSettings.theme.color is an empty string, so defaultSettings.theme.color is used. userSettings.theme.font is null, so defaultSettings.theme.font is used.

Example 4: Function Parameters with Defaults

When dealing with function parameters, you might want to provide default values for missing arguments.

function greet(name, greeting) {
  name = name ?? 'Guest';
  greeting = greeting || 'Hello';

  console.log(`${greeting}, ${name}!`);
}

greet(); // Output: 'Hello, Guest!'
greet('Alice'); // Output: 'Hello, Alice!'
greet('Bob', 'Hi'); // Output: 'Hi, Bob!'
greet(null, 'Hey'); // Output: 'Hey, Guest!'
Copy after login

In this example, the name parameter uses the ?? operator to set a default value of 'Guest' if name is null or undefined. The greeting parameter uses the || operator to set a default value of 'Hello' if greeting is any falsy value other than null or undefined.

Example 5: Combining with Optional Chaining

Optional chaining (?.) can be combined with || and ?? to handle deeply nested object properties safely.

let user = {
  profile: {
    name: 'John Doe'
  }
};

let userName = user?.profile?.name || 'Anonymous';
let userEmail = user?.contact?.email ?? 'No Email Provided';

console.log(userName); // Output: 'John Doe'
console.log(userEmail); // Output: 'No Email Provided'
Copy after login

In this example, optional chaining ensures that if any part of the property path does not exist, it returns undefined, preventing errors. The || and ?? operators then provide appropriate default values.

Best Practices and Use Cases

  1. Use || for Broad Defaulting:

    • When you need to provide default values for a range of falsy conditions (e.g., empty strings, 0, NaN).
  2. Use ?? for Precise Nullish Checks:

    • When you specifically want to handle null or undefined without affecting other falsy values.
  3. Combining Both:

    • Use a combination of || and ?? for complex scenarios where you need to handle both truthy/falsy values and nullish values distinctly.

FAQs

What does the Logical OR (||) operator do?
The Logical OR (||) operator returns the first truthy value among its operands or the last operand if none are truthy.

When should I use the Nullish Coalescing (??) operator?
Use the Nullish Coalescing (??) operator when you need to handle null or undefined specifically without treating other falsy values like 0 or empty strings as nullish.

Can I use both operators together?
Yes, you can use both || and ?? together to handle different types of values and ensure your code logic covers various cases effectively.

How does || handle empty strings?
The || operator treats empty strings as falsy, so it will return the next operand if the first is an empty string.

Is the Nullish Coalescing (??) operator supported in all browsers?
The ?? operator is supported in modern browsers and environments that support ES2020. For older environments, you may need to use a transpiler like Babel.

What are the differences between || and ?? operators?
The main difference is that || considers several values as falsy (e.g., 0, '', false), while ?? only treats null and undefined as nullish values.

Conclusion

Understanding the differences between the Logical OR (||) and Nullish Coalescing (??) operators in JavaScript is crucial for writing robust and bug-free code. The || operator is great for broad defaulting scenarios, while ?? is perfect for handling nullish values with precision. By using these operators appropriately, you can ensure your code handles various data states effectively, providing a seamless user experience.

The above is the detailed content of Unlocking JavaScript: Logical OR (||) vs Nullish Coalescing Operator (??). For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template