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.
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.
result = operand1 || operand2;
The || operator evaluates from left to right, returning the first operand if it is truthy; otherwise, it evaluates and returns the second operand.
let userInput = ''; let defaultText = 'Hello, World!'; let message = userInput || defaultText; console.log(message); // Output: 'Hello, World!'
In this example, userInput is an empty string (falsy), so defaultText is returned.
let firstName = null; let lastName = 'Doe'; let name = firstName || lastName || 'Anonymous'; console.log(name); // Output: 'Doe'
Here, firstName is null (falsy), so lastName is returned as it is truthy.
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.
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.
result = operand1 ?? operand2;
The ?? operator returns the right-hand operand when the left-hand operand is null or undefined. Otherwise, it returns the left-hand operand.
let userInput = ''; let defaultText = 'Hello, World!'; let message = userInput ?? defaultText; console.log(message); // Output: ''
In this example, userInput is an empty string, which is not null or undefined, so it is returned.
let firstName = null; let lastName = 'Doe'; let name = firstName ?? lastName ?? 'Anonymous'; console.log(name); // Output: 'Doe'
Here, firstName is null, so lastName is returned as it is neither null nor undefined.
let value1 = 0; let value2 = ''; let resultOR = value1 || 'default'; let resultNullish = value1 ?? 'default'; console.log(resultOR); // Output: 'default' console.log(resultNullish); // Output: 0
In this example, 0 is considered falsy by the || operator but is a valid value for the ?? operator.
let userInput = null; let fallbackText = 'Default Text'; let message = (userInput ?? fallbackText) || 'Fallback Message'; console.log(message); // Output: 'Default Text'
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.
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'
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.
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!'
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.
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'
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.
Use || for Broad Defaulting:
Use ?? for Precise Nullish Checks:
Combining Both:
논리 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!