Home > Web Front-end > JS Tutorial > body text

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

王林
Release: 2024-07-28 09:23:43
Original
812 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:

    • ||의 조합을 사용하세요 그리고 ?? 참/거짓 값과 null 값을 모두 명확하게 처리해야 하는 복잡한 시나리오의 경우.

자주 묻는 질문

논리 OR(||) 연산자의 기능은 무엇인가요?
논리 OR(||) 연산자는 피연산자 중 첫 번째 진실 값을 반환하거나 진실이 아닌 경우 마지막 피연산자를 반환합니다.

Nullish Coalescing(??) 연산자는 언제 사용해야 하나요?
0과 같은 거짓 값이나 빈 문자열을 null로 처리하지 않고 특별히 null 또는 정의되지 않음을 처리해야 하는 경우 Nullish Coalescing(??) 연산자를 사용하세요.

두 연산자를 함께 사용할 수 있나요?
예, 둘 다 사용할 수 있습니다 || 그리고 ?? 다양한 유형의 값을 처리하고 코드 논리가 다양한 사례를 효과적으로 처리하도록 보장합니다.

어떻게 || 빈 문자열을 처리하시겠습니까?
|| 연산자는 빈 문자열을 거짓으로 처리하므로 첫 번째 피연산자가 빈 문자열이면 다음 피연산자를 반환합니다.

Nullish Coalescing(??) 연산자는 모든 브라우저에서 지원되나요?
?? 연산자는 ES2020을 지원하는 최신 브라우저 및 환경에서 지원됩니다. 이전 환경의 경우 Babel과 같은 트랜스파일러를 사용해야 할 수도 있습니다.

||의 차이점은 무엇인가요? 그리고 ?? 운영자?
주요 차이점은 || 여러 값을 거짓(예: 0, '', false)으로 간주하는 반면 ?? null 및 undefound는 null 값으로만 ​​처리됩니다.

결론

JavaScript의 논리 OR(||) 연산자와 Nullish Coalescing(??) 연산자 간의 차이점을 이해하는 것은 강력하고 버그 없는 코드를 작성하는 데 중요합니다. || 연산자는 광범위한 불이행 시나리오에 적합하고 ?? null 값을 정밀하게 처리하는 데 적합합니다. 이러한 연산자를 적절하게 사용하면 코드가 다양한 데이터 상태를 효과적으로 처리하여 원활한 사용자 경험을 제공할 수 있습니다.

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!