CodersTechZone
  • .NET
    • C#
    • ASP.Net
  • HTML
  • Javascript
  • CSS
  • Database
    • SQL Server
    • MYSql
    • Oracle
  • AI
  • TechNews
  • Web-Stories

JavaScript Double Question Mark vs Or: A Comprehensive Guide

Shawpnendu Bikash Maloroy

June 23, 2024
JavaScript Double Question Mark vs Or - A Comprehensive Guide
Spread the love

“JavaScript double question mark vs or”: Two common operators in JavaScript that often confuse beginners and even experienced programmers are the double question mark (??) and the OR (||) operator.

The JS OR operator || uses the right value if left is false, while the double question mark?? uses the right value if left is null or undefined.

In this article, we will explore these two operators, understand their differences, and learn when to use each one. We’ll also include some frequently asked questions (FAQs) to help you further understand these concepts.

Table of Contents

  • What is the Double Question Mark (??) Operator?
    • Syntax
    • Code Example
  • What is the OR (||) Operator?
    • Syntax
    • Code Example
  • JavaScript Double Question Mark vs Or: Key Differences Explained
    • Handling False Values
    • Use Cases
    • Table of Differences
  • When to Use the Double Question Mark (??) Operator
    • Code Example
  • When to Use the OR (||) Operator
    • Code Example
  • JavaScript Double Question Mark vs Or: Practical Examples
    • Code Example 1: User Input
    • Code Example 2: Function Parameters
    • Example 3: Configuration Settings
  • Conclusion
  • FAQs on JavaScript Double Question Mark vs Or
  • Can I use ?? with || together?
  • What happens if I use ?? with a non-nullish falsy value?
  • Can I use ?? with multiple values?
  • How does || handle non-boolean values?
  • Are there performance differences between ?? and ||?

What is the Double Question Mark (??) Operator?

The double question mark (??) operator, also known as the nullish coalescing operator, is a logical operator that returns the right-hand side operand when the left-hand side operand is null or undefined. Otherwise, it returns the left-hand side operand.

Syntax

let result = leftOperand ?? rightOperand;

Code Example

let name = null; 
let displayName = name ?? "Guest"; 

console.log(displayName); // Output: Guest

In the example above, name is null, so the ?? operator returns “Guest”.

What is the OR (||) Operator?

The OR (||) operator is an older and more commonly known operator in JavaScript. It returns the first truthy value encountered, or the last value if none are true.

In more detail, the OR (||) operator is a logical operator that returns the right-hand side operand when the left-hand side operand is false. In JavaScript, false values include false, 0, “” (empty string), null, undefined, and NaN. Otherwise, it returns the left-hand side operand.

Syntax

let result = leftOperand || rightOperand;

Code Example

let age = 0; 
let displayAge = age || 18; 

console.log(displayAge); // Output: 18

In this example, age is 0, which is a falsy value, so the || operator returns 18.

buymeacoffee

JavaScript Double Question Mark vs Or: Key Differences Explained

Understanding the differences between these two operators is crucial for using them correctly. Here are the main differences:

Handling False Values

  • ??: Only checks for null or undefined.
  • ||: Checks for any false value (false, 0, "", null, undefined, NaN).

Use Cases

  • ??: Use when you want to handle null or undefined specifically.
  • ||: Use when you want to handle all false values.

Table of Differences

FeatureDouble Question Mark (??)OR (||)
Introduced inECMAScript 2020 (ES11)ECMAScript 1
Checks fornull or undefinedAny false value
Common Use CaseDefault values for null or undefinedDefault values for any false values
Examplelet result = value1 ?? value2;let result = value1 || value2;
JavaScript double question mark vs or – complete list

Note

The difference between the operators Double Question Mark (??) and OR (||) is that one is used to check nullish values and another one is to check falsy values. But there are many cases where we have not found any differences between them. In JS, all null values are also false, but not every false value is null. To understand more, check out our below list of code examples carefully.

When to Use the Double Question Mark (??) Operator

The ?? operator is ideal when you only want to check for null or undefined values and want to allow other falsy values.

Note

More clearly, if the left value is null or undefined and you want to get the right value, then use the nullish coalescing operator ??.

buymeacoffee

Code Example

let user = { name: "Alice", age: 0 }; 
let userAge = user.age ?? 18; 

console.log(userAge); // Output: 0

In this example, user.age is 0, which is a valid value and not null or undefined. Therefore, ?? returns 0.

When to Use the OR (||) Operator

The || operator is useful when you want to provide a default value for any falsy operand.

Code Example

let user = {
    name: "Bob",
    age: 0
};
let userAge = user.age || 18;
console.log(userAge); // Output: 18

Here, user.age is 0, a false value. Therefore, || returns 18.

Note

The JS OR operator || will be very problematic in cases where the left value contains an empty string such as "" or 0 or false (because all are false values). To avoid confusion, look at our practical examples section mentioned below.

JavaScript Double Question Mark vs Or: Practical Examples

Let’s look at some practical examples to understand how we can use both operators better.

Code Example 1: User Input

// JavaScript double question mark vs or
// check differences
let userInput = "";
let message = userInput || "Default message";
console.log(message); // Output: Default message

let secureInput = userInput ?? "Default message";
console.log(secureInput); // Output: ""

Code Example 2: Function Parameters

function greet(name) {
    let userName = name ?? "Guest";
    console.log("Hello, " + userName);
}

// JavaScript double question mark vs or
greet(null); // Output: Hello, Guest
greet("");   // Output: Hello, 

Example 3: Configuration Settings

let config = {
    timeout: 0
};

// JavaScript double question mark vs or
// Understand numeric comparisons
let timeoutSetting = config.timeout ?? 1000;
console.log(timeoutSetting); // Output: 0

let fallbackSetting = config.timeout || 1000;
console.log(fallbackSetting); // Output: 1000

Conclusion

JavaScript double question mark vs or: Understanding the differences between the double question mark (??) and OR (||) operators is essential for writing effective JavaScript code. While both operators can provide default values, they serve different purposes and handle different types of values. Use ?? when dealing specifically with null or undefined, and use || when you need to handle a broader range of falsy values. With this knowledge, you can make better decisions and write cleaner, more efficient code.

If you have any more questions, feel free to refer to the FAQ section or leave a comment below. Happy coding!

FAQs on JavaScript Double Question Mark vs Or

Can I use ?? with || together?

Yes, you can combine both operators in your code. For example:

let user = null;
let age = 0;
let defaultUser = “Guest”;
let defaultAge = 18;
let currentUser = user ?? defaultUser;
let currentAge = age || defaultAge;
console.log(currentUser); // Output: “Guest”
console.log(currentAge); // Output: 18

In this example, ?? handles null for user, and || handles the falsy value 0 for age.

What happens if I use ?? with a non-nullish falsy value?

If you use ?? with a non-nullish falsy value, it will not consider it and will return the original value:

let value = 0;
let defaultValue = 10;
let result = value ?? defaultValue;
console.log(result); // Output: 0

Can I use ?? with multiple values?

Yes, you can chain multiple ?? operators:

let value1 = null;
let value2 = undefined;
let value3 = “Hello”;
let result = value1 ?? value2 ?? value3;
console.log(result); // Output: “Hello”

How does || handle non-boolean values?

The || operator returns the first truthy value it gets or the last value if none are truthy, regardless of whether they are boolean:

let value1 = 0;
let value2 = “Hello”;
let value3 = false;
let result = value1 || value2 || value3;
console.log(result); // Output: “Hello”

Are there performance differences between ?? and ||?

The performance differences between ?? and || are negligible in most use cases. However, using the correct operator based on your needs can make your code clearer and more maintainable.

Shawpnendu Bikash Maloroy
Shawpnendu Bikash Maloroy

๐Ÿ‹๏ธโ€โ™‚๏ธ Discover Code Blocks From 20+ yrs JS Expert
๐Ÿ’ฅ Asp.net C# Developer
๐Ÿ† Solution Architect
๐Ÿ‘จโ€โœˆ๏ธ Database Administrator
๐Ÿ“ข Speaker
๐ŸŽ“ MCTS since 2009

Share this:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on X (Opens in new window) X

Spread the love
ยซPrevious
Nextยป

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • 5 Lesser-Known JavaScript Functions
    5 Lesser-Known JavaScript Functions to Boost Your Coding Efficiency
  • 7 Weird JavaScript Tricks That Look Like Bugs
    7 Weird JavaScript Tricks That Look Like Bugs (#3 Will Shock You!)
  • Build a JavaScript Gamer Journal in 8 Lines
    ๐ŸŽฎ Build a JavaScript Gamer Journal in 8 Lines: Track Your Wins Like a Pro! ๐Ÿ†
  • JavaScript Pet Feeder Reminder in 7 Lines
    How to Code a Simple JavaScript Pet Feeder Reminder in 7 Lines: Feed Your Pet Like a Coding Boss! ๐Ÿถ
  • 10-line calculator JavaScript
    Build a Simple Calculator in JavaScript: 10 Lines to Wow Your Friends!

About-CodersTech Zone |  Contact |  Disclaimer |  Fact-Checking policy |  Affiliate Disclosure |  Privacy Policy

Copyright ยฉ 2024 CodersTechZone.com