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

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

Jul 28, 2024 am 09:23 AM

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!

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1267
29
C# Tutorial
1239
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

See all articles