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:
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.
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!