Nullish coalescing operator '??'

The nullish coalescing operator is written as two question marks ?? .

As it treats null and undefined similarly, we’ll use a special term here, in this article. For brevity, we’ll say that a value is “defined” when it’s neither null nor undefined .

The result of a ?? b is:

  • if a is defined, then a ,
  • if a isn’t defined, then b .

In other words, ?? returns the first argument if it’s not null/undefined . Otherwise, the second one.

The nullish coalescing operator isn’t anything completely new. It’s just a nice syntax to get the first “defined” value of the two.

We can rewrite result = a ?? b using the operators that we already know, like this:

Now it should be absolutely clear what ?? does. Let’s see where it helps.

The common use case for ?? is to provide a default value.

For example, here we show user if its value isn’t null/undefined , otherwise Anonymous :

Here’s the example with user assigned to a name:

We can also use a sequence of ?? to select the first value from a list that isn’t null/undefined .

Let’s say we have a user’s data in variables firstName , lastName or nickName . All of them may be not defined, if the user decided not to fill in the corresponding values.

We’d like to display the user name using one of these variables, or show “Anonymous” if all of them are null/undefined .

Let’s use the ?? operator for that:

Comparison with ||

The OR || operator can be used in the same way as ?? , as it was described in the previous chapter .

For example, in the code above we could replace ?? with || and still get the same result:

Historically, the OR || operator was there first. It’s been there since the beginning of JavaScript, so developers were using it for such purposes for a long time.

On the other hand, the nullish coalescing operator ?? was added to JavaScript only recently, and the reason for that was that people weren’t quite happy with || .

The important difference between them is that:

  • || returns the first truthy value.
  • ?? returns the first defined value.

In other words, || doesn’t distinguish between false , 0 , an empty string "" and null/undefined . They are all the same – falsy values. If any of these is the first argument of || , then we’ll get the second argument as the result.

In practice though, we may want to use default value only when the variable is null/undefined . That is, when the value is really unknown/not set.

For example, consider this:

  • so the result of || is the second argument, 100 .
  • so the result is height “as is”, that is 0 .

In practice, the zero height is often a valid value, that shouldn’t be replaced with the default. So ?? does just the right thing.

The precedence of the ?? operator is the same as || . They both equal 3 in the MDN table .

That means that, just like || , the nullish coalescing operator ?? is evaluated before = and ? , but after most other operations, such as + , * .

So we may need to add parentheses in expressions like this:

Otherwise, if we omit parentheses, then as * has the higher precedence than ?? , it would execute first, leading to incorrect results.

Using ?? with && or ||

Due to safety reasons, JavaScript forbids using ?? together with && and || operators, unless the precedence is explicitly specified with parentheses.

The code below triggers a syntax error:

The limitation is surely debatable, it was added to the language specification with the purpose to avoid programming mistakes, when people start to switch from || to ?? .

Use explicit parentheses to work around it:

The nullish coalescing operator ?? provides a short way to choose the first “defined” value from a list.

It’s used to assign default values to variables:

The operator ?? has a very low precedence, only a bit higher than ? and = , so consider adding parentheses when using it in an expression.

It’s forbidden to use it with || or && without explicit parentheses.

Lesson navigation

  • © 2007—2024  Ilya Kantor
  • about the project
  • terms of usage
  • privacy policy

The Nullish Coalescing Operator ?? in JavaScript

The nullish coalescing operator provides a concise syntax for setting a default value if the given value is nullish . null and undefined are the only nullish values in JavaScript.

Nullish coalescing is typically used for assigning default values. Older JavaScript code often used || for assigning default values, but || is error prone because it captures all falsy values , like 0 , empty string, and false .

Nullish Coalescing Assignment

The nullish coalescing assignment operator is similar to the nullish coalescing operator, just for assignments. Nullish coalescing assignment only assigns the value if the left hand side is nullish. x ??= y is equivalent to x = x ?? y .

Pre-ES2020 Alternative

The nullish coalescing operator was introduced in ES2020 , which makes it a relatively new addition to the JavaScript language. For example, the nullish coalescing operator isn't supported in Node.js 12. However, there is a concise alternative with the ternary operator that works in any version of JavaScript.

More Fundamentals Tutorials

  • The `setTimeout()` Function in JavaScript
  • JavaScript Array flatMap()
  • How to Get Distinct Values in a JavaScript Array
  • Check if a Date is Valid in JavaScript
  • Encode base64 in JavaScript
  • Check if URL Contains a String
  • JavaScript Add Month to Date
  • ASP.NET MVC
  • ASP.NET WebForms

Nullish coalescing operator (??)

In a programming language like JavaScript, as well as many other programming languages, a lot of effort is being put into making sure that a variable or return value actually HAS a value and isn't in fact NULL (or undefined in JavaScript).

So, before using a variable, you will often need to make sure that it has a value, unless you already know this to be true. A place where this is very common is inside of a function, where you want to make certain that any parameters you're going to use actually has a value. Here's an example from another article in this tutorial:

Since JavaScript doesn't really do any validation when it comes to the amount or type of arguments you pass to a function, the above function could be called like this:

The result would not make sense, since the first parameter is NULL and the two others would be undefined - you can't really do math on that. Therefore, we would usually do some validation on the parameters, like this:

Using the ?? operator

That's not very good looking, but fortunately for us, JavaScript comes with a very helpful operator: The Nullish coalescing operator (??) . It works like this:

It will simply return either the left or the right part of the statement, depending on whether the left part is NULL or undefined or not. It's mostly just syntactic sugar, but it will make the above code shorter and easier on the eye:

So in this case, if one or several of the parameters doesn't have a value, it will fallback to 0. You are free to provide any type of fallback value, like a string or the return value of another function - the sky is the limit here.

Prior to the introduction of the Nullish coalescing operator (??), the logical OR operator (||) was used a lot to accomplish the same as the ?? operator. And you may still see code like this a lot:

As you can see, I have replaced the ?? operator with the || operator. And if you do the same, for the example above, you will see the exact same, and expected, behavior: The parameters will fall back to the value of 0 if they are not provided. However, there's a very important difference between the two operators : The ?? operator will only react to NULL or undefined, while the || operator will respond negatively to any "falsy" value.

As we talked about previously in this tutorial, "falsy" is used to describe any value that is actually false or could be considered false in a boolean context. This includes the number 0, empty text strings and so on. Therefore, you should pay attention to which operator you use, because it will make a difference, as illustrated by this example:

I use the || operator for the first message and the ?? for the second message. Notice how they react differently to the various arguments I supply them with. The fallback message for msg2 is only used in the first call to the function, because it responds only to being undefined .

Nullish coalescing assignment: ??=

The nullish coalescing assignment operator (sometimes referred to as the logical nullish assignment operator ) will allow you to assign a value to a variable, but only if value of this variable is NULL or undefined, without checking it first. So, before this operator, you could see a piece of code like this:

Or you could use the Nullish coalescing operator to make it a bit shorter:

But why not go all the way and make it even shorter, using the Nullish coalescing assignment operator , like this:

Again, this is just syntactic sugar, but it is a bit easier to write and perhaps even easier to read? I will let you be the judge of that.

At this point, you may be a bit confused and ask your self: Are there any differences between these two operators? And yes, there is - a subtle one, but still a difference. While the Nullish coalescing operator (??) will return the left part of the statement if its not NULL or undefined, the Nullish coalescing assignment operator (??=) will not return anything - it only works for assigning a value to the left part of the statement in case its NULL or undefined.

Use the Nullish coalescing operator (??) to provide a fallback value in case the variable in question is NULL or undefined. As an alternative, you can use the logical OR operator (||), which will use the fallback value for anything that can be considered false, including NaN, 0, empty text strings and so on.

If you're just looking to assign a value to a variable in case the variable is NULL or undefined, you can use the Nullish coalescing assignment operator (??=).

Home » JavaScript Tutorial » JavaScript Nullish Coalescing Operator

JavaScript Nullish Coalescing Operator

Summary : in this tutorial, you’ll learn about the JavaScript nullish coalescing operator ( ?? ) that accepts two values and returns the second value if the first one is null or undefined .

Introduction to the JavaScript nullish coalescing operator

ES2020 introduced the nullish coalescing operator denoted by the double question marks ( ?? ). The nullish coalescing operator is a logical operator that accepts two values:

The nullish coalescing operator returns the second value ( value2 ) if the first value ( value2 ) is null or undefined . Technically, the nullish coalescing operator is equivalent to the following block:

A nullish value is a value that is either  null  or  undefined .

The following example uses the nullish coalescing operator ( ?? ) to return the string 'John' because the first value is null :

And this example returns 28 because the first value is undefined :

Why nullish coalescing operator

When assigning a default value to a variable , you often use the logical OR operator ( || ). For example:

In this example, the count variable is undefined , it is coerced to false . Therefore, the result is 1 .

However, the logical OR operator ( || ) sometimes is confusing if you consider 0 or empty strings '' as a valid value like this:

The result is 1, not 0, which you may not expect.

The nullish coalescing operator helps you to avoid this pitfall. It only returns the second value when the first one is either null or undefined .

The nullish coalescing operator is short-circuited

Similar to the logical OR and AND operators , the nullish coalescing operator does not evaluate the second value if the first operand is neither undefined nor null .

For example:

In this example, the operator ?? does not evaluate the second expression that displays the “Hi” to the console because the first value is 1 , which is not null or undefined .

The following example evaluates the second expression because the first one is undefined :

Chaining with the AND or OR operator

A SyntaxError will occur if you combine the logical AND or OR operator directly with the nullish coalescing operator like this:

However, you can avoid this error by wrapping the expression on the left of the ?? operator in parentheses to explicitly specify the operator precedences:

  • The nullish coalescing operator ( ?? ) is a logical operator that accepts two values and returns the second value if the first one is null or undefined .
  • The nullish coalescing operator is short-circuited and cannot directly combine with the logical AND or OR operator.

How the Nullish Coalescing Operator Works in JavaScript

Yogesh Chavan

ES11 has added a nullish coalescing operator which is denoted by double question marks, like this: ?? .

In this article, we will explore why it's so useful and how to use it.

Let's get started.

Background Information

In JavaScript, there is a short-circuit logical OR operator || .

The || operator returns the first truthy value.

The following are the only six values that are considered to be falsy values in JavaScript.

  • ""(empty string)

So if anything is not in the above list, then it will be considered a truthy value.

Truthy and Falsy values are the non-boolean values that are coerced to true or false when performing certain operations.

As the || operator returns the first truthy value, in the above code, the result will be the value stored in value1 which is 1 .

If value1 is null , undefined , empty or any other falsy value, then the next operand after the || operator will be evaluated and that will the result of the total expression.

Here, because value1 is 0, value2 will be checked. As it's a truthy value, the result of the entire expression will be the value2 .

The issue with the || operator is that it doesn’t distinguish between false , 0 , an empty string "" , NaN , null and undefined . They all are considered as falsy values.

If any of these is the first operand of || , then we’ll get the second operand as the result.

Why JavaScript Needed the Nullish Coalescing Operator

The || operator works great but sometimes we only want the next expression to be evaluated when the first operand is only either null or undefined .

Therefore, ES11 has added the nullish coalescing operator.

In the expression x ?? y ,

  • If x is either null or undefined then only result will be y .
  • If x is not null or undefined then the result will be x .

This will make the conditional checks and debugging code an easy task.

Try it yourself

So from all of the above examples, it’s clear that the result of the operation x ?? y is y only when x is either undefined or null .

In all the other cases, the result of the operation will always be x .

As you have seen, the nullish coalescing operator is really useful when you only care about the null or undefined value for any variable.

Starting with ES6, there are many useful additions to JavaScript like

  • ES6 Destructuring
  • Import and Export Syntax
  • Arrow functions
  • Async/await
  • Optional chaining operator

and a lot more.

You can learn everything about all the ES6+ features in detail in the Mastering Modern JavaScript book.

You can get the Mastering Modern JavaScript book at 40% discount .

Subscribe to my weekly newsletter to join 1000+ other subscribers to get amazing tips, tricks, articles and discount deals directly in your inbox.

Full Stack Developer | Freelancer | JavaScript | React | Nodejs. Loves sharing knowledge through technical articles. Dev.to: https://dev.to/myogeshchavan97 https://linktr.ee/myogeshchavan97

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Nullish Coalescing in JavaScript: A Developer’s Guide

With the ever-evolving landscape of JavaScript, it’s crucial for developers to stay abreast of the latest features and enhancements that the language offers. One such feature, introduced in ECMAScript 2020 (ES11), is the Nullish Coalescing Operator ( ?? ). This powerful operator provides a more intuitive and cleaner way to deal with values that might be null or undefined . In this guide, we’ll dive deep into the nuances of Nullish Coalescing in JavaScript, enriched with various code examples to solidify your understanding.

Understanding Nullish Values

Before delving into Nullish Coalescing, it’s important to differentiate between JavaScript’s falsy values and nullish values. Falsy values include false , 0 , -0 , 0n , "" (empty string), null , undefined , and NaN . Among these, null and undefined are considered nullish, indicating the absence of any value.

What is Nullish Coalescing?

The Nullish Coalescing Operator ( ?? ) is a logical operator that returns its right-hand side operand when its left-hand side operand is either null or undefined , and otherwise returns its left-hand side operand. This is distinctly different from the JavaScript logical OR ( || ) operator, which returns the right-hand operand if the left-hand operand is any falsy value.

Advantages of Nullish Coalescing

The principal benefit of using the Nullish Coalescing Operator is that it prevents JavaScript’s default behavior of coercing falsy values to false . This behavior can lead to unintuitive and often undesirable outcomes when working with variables that may legitimately hold falsy values like 0 , false , or an empty string ( "" ).

Practical Use Cases

Nullish Coalescing shines in scenarios where you need to set default values. Consider the example of setting a default greeting message:

This ensures that 'Welcome back!' is only used if user.customGreeting is null or undefined , not just any falsy value.

Combining with Optional Chaining

When used in conjunction with Optional Chaining ( ?. ), Nullish Coalescing becomes even more potent, allowing developers to gracefully handle deeply nested objects:

This expression will output 'Location unknown' if either userProfile is null or undefined , or if userProfile.location or userProfile.location.city does not exist.

Nullish Coalescing in JavaScript offers a robust solution for handling null and undefined values explicitly, allowing for cleaner, more predictable code. By understanding and utilizing this operator, developers can avoid common pitfalls associated with falsy value coercion and ensure their applications handle variable states more gracefully. As JavaScript continues to evolve, features like Nullish Coalescing highlight the language’s commitment to developer productivity and code safety.

Experiment with the Nullish Coalescing Operator in your projects and observe how it can simplify your conditional logic and streamline your codebase. Embrace ES2020’s enhancements, and continue to explore the rich features JavaScript has to offer.

Next Article: Let, Const, and Var in Modern JavaScript

Previous Article: JavaScript Promise.allSettled() method (with examples)

Series: JavaScript Basics

Related Articles

  • JavaScript: Press ESC to exit fullscreen mode (2 examples)
  • Can JavaScript programmatically bookmark a page? (If not, what are alternatives)
  • Dynamic Import in JavaScript: Tutorial & Examples (ES2020+)
  • JavaScript: How to implement auto-save form
  • JavaScript: Disable a Button After a Click for N Seconds
  • JavaScript: Detect when a Div goes into viewport
  • JavaScript Promise.any() method (basic and advanced examples)
  • Using logical nullish assignment in JavaScript (with examples)
  • Understanding WeakRef in JavaScript (with examples)
  • JavaScript Numeric Separators: Basic and Advanced Examples
  • JavaScript: How to Identify Mode(s) of an Array (3 Approaches)
  • JavaScript: Using AggregateError to Handle Exceptions

Search tutorials, examples, and resources

  • PHP programming
  • Symfony & Doctrine
  • Laravel & Eloquent
  • Tailwind CSS
  • Sequelize.js
  • Mongoose.js
  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

Nullish coalescing operator (??)

The nullish coalescing ( ?? ) operator is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined , and otherwise returns its left-hand side operand.

Description

The nullish coalescing operator can be seen as a special case of the logical OR ( || ) operator . The latter returns the right-hand side operand if the left operand is any falsy value, not only null or undefined . In other words, if you use || to provide some default value to another variable foo , you may encounter unexpected behaviors if you consider some falsy values as usable (e.g., '' or 0 ). See below for more examples.

The nullish coalescing operator has the fifth-lowest operator precedence , directly lower than || and directly higher than the conditional (ternary) operator .

It is not possible to combine both the AND ( && ) and OR operators ( || ) directly with ?? . A syntax error will be thrown in such cases.

Instead, provide parenthesis to explicitly indicate precedence:

Using the nullish coalescing operator

In this example, we will provide default values but keep values other than null or undefined .

Assigning a default value to a variable

Earlier, when one wanted to assign a default value to a variable, a common pattern was to use the logical OR operator ( || ):

However, due to || being a boolean logical operator, the left-hand-side operand was coerced to a boolean for the evaluation and any falsy value (including 0 , '' , NaN , false , etc.) was not returned. This behavior may cause unexpected consequences if you consider 0 , '' , or NaN as valid values.

The nullish coalescing operator avoids this pitfall by only returning the second operand when the first one evaluates to either null or undefined (but no other falsy values):

Short-circuiting

Like the 'OR' and 'AND' logical operators, the right-hand side expression is not evaluated if the left-hand side proves to be neither null nor undefined .

Relationship with the optional chaining operator (?.)

The nullish coalescing operator treats undefined and null as specific values. So does the optional chaining operator ( ?. ) , which is useful to access a property of an object which may be null or undefined . Combining them, you can safely access a property of an object which may be nullish and provide a default value if it is.

Specifications

Specification

Browser compatibility

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

  • Nullish coalescing assignment ( ??= )
  • Optional chaining ( ?. )
  • Logical OR ( || )
  • Default parameters

Null Coalescing Operator in JavaScript with ECMAScript 2020

js null coalescing assignment

  • Introduction

When working in a request-response lifecycle , you want to make sure that a response with the wanted body - or at least an informative response arrives so the client that requested the data stays in the loop. In case of null values , you'll probably want to return a different result.

JavaScript made sure this can be handled with its nullish operator also known as the Null Coalescing Operator , which was added to the language with ECMAScript 2020 . With it, you can either return a value or assign it to some other value, depending on a boolean expression.

This can be used to return default values if another value is missing, or to return different values based on any other boolean expression.

The Null Coalescing Operator belongs to the group of short-circuiting logical operators , which we'll take a look at in a moment.

It's somewhat similar to the Conditional Operator , which is sometimes known as the Ternary Operator :

In this guide, we'll be taking a look at the nullish/Null Coalescing Operator, short-circuiting and truthy and falsy values - through practical examples.
  • What is short-circuiting?

JavaScript evaluates operators from left to right. With exclusive operators where we need both values to evaluate to true, it's sometimes enough to check just the first evaluation statement.

If the left side of the operator is false , regardless of the right side, the operator results in false , so there's no point in evaluating the other side, and it's skipped to preserve computational power.

This process is called short-circuiting .

Before ES2020, JavaScript only had two short-circuit logical operators:

  • Logical operator AND - &&
  • Logical operator OR - ||

With the new update, JavaScript introduced another one:

  • Null Coalescing operator - ??

Short-circuiting itself makes code more efficient because less evaluations need to happen, though, via the Null Coalescing operator, we can also alter the code logic based on a short-circuiting operation.

For instance:

This code will result in:

Though, we could also ditch the if statement fully and use a short-circuit AND operator instead to shorten the statements:

(x+y) > 20 evaluates to true so the next block is entered, and the message is printed.

Where is short-circuiting here?

If the (x+y) > 20 was falsy (we'll talk about this in a second), the JavaScript interpreter wouldn't even look at the second part of the expression, and the block would never run.

Similarly enough, we can use the logical OR operator in a similar way:

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Naturally, this results in:

These examples are pretty simple, yet logical operators can solve a lot of practical problems and make your code a lot cleaner. However, if not used properly, you might cause yourself a headache.

  • Truthy and Falsy values

When working with logical operators, you'll come around the terms truthy value and falsy value .

A truthy value is any value that isn't:

  • '' - empty string
  • NaN - Not a Number

All these values are considered falsy .

In JavaScript, all the falsy values are evaluated as false when used in loops or if statements and all the truthy values are evaluated as true .

Now that we've got the prerequisites covered, let's finally take a look at the Nullish Operator .

  • Nullish Coalescing Operator

The Nullish Operator checks whether the value is nullish , not falsy . A nullish value is undefined or null .

This allows us to assign default non-null values to variables when we're unsure of the results.

For instance, let's mock a user service that retrieves a user from a database and returns their name. There's a 10% chance that the user doesn't exist, which is regulated by a Math.random() call. In 10 calls to the database, we're likely to see at least one missing user - denoted by a null result:

The code will output either the name or a message denoting the lack of the user's existence in the database, though this requires us to perform null-checks in the if statement.

This results in:

By happenstance, this seems to be an odd run - 3 null results! This code works just fine, and handles null cases if the database returns a null value.

Alternatively, we could've used something much more concise:

Using a conditional operator , we've returned either null or John Doe with their respective ID. If Math.random() > 0.9 , null is returned, so there's a 10% probability it'll be returned on each call to the database.

Then, assuming possible null values - we've used the Nullish Operator to assign a new value to the user result if it turns out to be null . If db.find() returns null , the right-hand value kicks in and is returned instead.

This code is much cleaner and shorter than the if-else statements, and if-else statements have a higher tendency to cascade and get even more complex. Though, chaining multiple short-circuiting operators gets hard to read as well, so it's not really advisable to replace all if-else blocks:

Do you know what this would print? Considering random possibilities, it'd likely take you a while to parse this manually and see which values you can anticipate. This code has a tendency to result in 1 with null and 4 in some cases, as the returned default value for the nullish operator in this case is another null . Typically, you won't use more than one, or two, operators in cases like these.

To wrap this up, the sole purpose of the nullish operator is to allow you to always return some kind of default value, instead of returning something that doesn't exist - which, in JavaScript, is what null and undefined mean.

You might also like...

  • JavaScript: Check if First Letter of a String is Upper Case
  • Using Mocks for Testing in JavaScript with Sinon.js
  • For-each Over an Array in JavaScript
  • Commenting Code in JavaScript - Types and Best Practices

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

In this article

js null coalescing assignment

Monitor with Ping Bot

Reliable monitoring for your app, databases, infrastructure, and the vendors they rely on. Ping Bot is a powerful uptime and performance monitoring tool that helps notify you and resolve issues before they affect your customers.

OpenAI

Vendor Alerts with Ping Bot

Get detailed incident alerts about the status of your favorite vendors. Don't learn about downtime from your customers, be the first to know with Ping Bot.

Supabase

© 2013- 2024 Stack Abuse. All rights reserved.

  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology

JavaScript Nullish Coalescing(??) Operator

The nullish coalescing (??) operator is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand. It’s commonly used to provide default values for variables.

Below are examples of the Nullish Coalescing Operator.

Example 1: In this example, we will see a basic function using the nullish coalescing operator

Example 2: The more common use case is to set default values for JSON objects as follows. 

Supported Browsers: The browsers supported by JavaScript Nullish Coalescing Operator are listed below:

  • Google Chrome
  • Edge  

Please Login to comment...

Similar reads.

  • Web Technologies
  • javascript-operators

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Web Development

What Is the JavaScript Logical Nullish Assignment Operator?

  • Daniyal Hamid
  • 24 Dec, 2021

Introduced in ES12, you can use the logical nullish assignment operator ( ??= ) to assign a value to a variable if it hasn't been set already. Consider the following examples, which are all equivalent:

The null coalescing assignment operator only assigns the default value if x is a nullish value (i.e. undefined or null ). For example:

In the following example, x already has a value, therefore, the logical nullish assignment operator would not set a default (i.e. it won't return the value on the right side of the assignment operator):

In case, you use the nullish assignment operator on an undeclared variable, the following ReferenceError is thrown:

This post was published 24 Dec, 2021 by Daniyal Hamid . Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post .

Nullish coalescing

What about default assignment while destructuring #, mixing and matching operators #, tell me about document.all #, support for nullish coalescing #.

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

How can I get eslint to accept the nullish-coalescing assignment?

The "nullish-coalescing assignment" operator, ??= , is a relatively recent introduction to JavaScript; but not all that recent... and yet, eslint , even newer versions like 8.38.0 , seem not to recognize it - and yields a syntax error about the assignment (the = after the ?? ). Here's the line I'm trying to get to pass the check:

Why is this happening? And - how can I tell eslint to accept this operator?

  • nullish-coalescing

einpoklum's user avatar

  • 1 Try using ECMAScript 2021 in the config? { "parserOptions": { "ecmaVersion": 2021 } } seems to remove the error for me –  evolutionxbox Commented Apr 24, 2023 at 14:21
  • I can't reproduce the problem. Picking the most restrictive options from the eslint configuration wizard and running it against the Try It example on the MDN page you link to, it complains only about console.log . You should provide a minimal reproducible example , including your eslint configuration and the lines of package.json that provide eslint and its plugins (for the specific versions). –  Quentin Commented Apr 24, 2023 at 14:23

You need to make sure ecmaVersion is set to "latest" or to 2021 (aka 12 ) or higher, so ESLint knows what version of JavaScript to parse (more in the configuration help ). Here's an ESLint playground example using ??= successfully with the version set to "latest" ; here's one where it doesn't work because the version is set to 2020.

Re your update showing this code:

...it's not an ESLint or ??= -specific thing, that's just not a valid place to use a compound assignment operator (any of them). Here's an example using += in JavaScript (no linter):

var a += 42; // ^−−−−−−−− SyntaxError: Unexpected token '+=' console.log(a);

In the normal case, you'd just want an assignment operator (ideally using let or const ; var shouldn't be used in new code):

In a very unusual situation where you had to declare a variable that might already be declared and use its current value if it's not nullish, you'd have to separate that into two parts:

But I wouldn't do that in new code. :-)

T.J. Crowder's user avatar

  • (Doh! Typo, if you see "2021" at the very end instead of "2020", hit refresh) –  T.J. Crowder Commented Apr 24, 2023 at 14:23
  • So, that itself didn't work for me, but I figured out it was because I had var at the beginning of the line, so perhaps you can update your answer accordingly. –  einpoklum Commented Apr 24, 2023 at 14:28
  • @einpoklum - Done. Was that just a mistake or was there something you were trying to do with that combination of var and ??= ? –  T.J. Crowder Commented Apr 24, 2023 at 14:36
  • 1 If you use it in global scope consider window.ObjectUtils ??= ... instead of using var . –  3limin4t0r Commented Apr 24, 2023 at 15:07
  • 1 @einpoklum - Yeah, or using globalThis instead of window nowadays. (That said: I'd suggest adopting modules as soon as convenient. :-) ) –  T.J. Crowder Commented Apr 24, 2023 at 15:20

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged javascript eslint lint nullish-coalescing or ask your own question .

  • The Overflow Blog
  • Ryan Dahl explains why Deno had to evolve with version 2.0
  • From PHP to JavaScript to Kubernetes: how one backend engineer evolved over time
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • What does a new user need in a homepage experience on Stack Overflow?

Hot Network Questions

  • Why don't we observe protons deflecting in J.J. Thomson's experiment?
  • Can pedestrians and cyclists use the Channel Tunnel?
  • Can objective morality be derived as a corollary from the assumption of God's existence?
  • Calculate the sum of numbers in a rectangle
  • Everyone hates this Key Account Manager, but company won’t act
  • Use greek letters not as part of a math equation
  • The hat-check problem
  • Fast circular buffer
  • How should I respond to a former student from my old institution asking for a reference?
  • Position of "aussi" when using question inversion
  • The McDonald's Option
  • Are Experimental Elixirs Magic Items?
  • Visualizing histogram of data on unit circle?
  • Sticker on caption phone says that using the captions can be illegal. Why?
  • "Knocking it out of the park" sports metaphor American English vs British English?
  • Why if gravity would be higher, designing a fully reusable rocket would be impossible?
  • Should I Inform My PhD Program About Not Completing My Master's Degree Due to Personal Challenges?
  • How to determine if a set is countable or uncountable?
  • Who said "If you don't do politics, politics will do you"?
  • Is there anything that stops the majority shareholder(s) from destroying company value?
  • Millennial reign and new Heaven and new earth
  • How to extract code into library allowing changes without workflow overhead
  • Display frac form in Forest automatically?
  • If you get pulled for secondary inspection at immigration, missing flight, will the airline rebook you?

js null coalescing assignment

IMAGES

  1. Learn JavaScript Nullish Coalescing Operator & Assignment in 10 Minutes

    js null coalescing assignment

  2. Nullish coalescing operator in JavaScript: Complete explanation

    js null coalescing assignment

  3. JavaScript Tutorial

    js null coalescing assignment

  4. JavaScript Nullish Coalescing Operator

    js null coalescing assignment

  5. JavaScript

    js null coalescing assignment

  6. What is Nullish coalescing operator "??" in JavaScript and How it Works

    js null coalescing assignment

COMMENTS

  1. Nullish coalescing assignment (??=)

    Visit Mozilla Corporation's not-for-profit parent, the Mozilla Foundation. Portions of this content are ©1998-2024 by individual mozilla.org contributors. Content available under a Creative Commons license. a Creative Commons license.

  2. Is there a "null coalescing" operator in JavaScript?

    beware of the JavaScript specific definition of null. there are two definitions for "no value" in javascript. 1. Null: when a variable is null, it means it contains no data in it, but the variable is already defined in the code. like this: var myEmptyValue = 1; myEmptyValue = null;

  3. Nullish coalescing operator

    The nullish coalescing operator is written as two question marks ??.. As it treats null and undefined similarly, we'll use a special term here, in this article. For brevity, we'll say that a value is "defined" when it's neither null nor undefined.. The result of a ?? b is:. if a is defined, then a,; if a isn't defined, then b.; In other words, ?? returns the first argument if it ...

  4. The Nullish Coalescing Operator ?? in JavaScript

    The nullish coalescing operator was introduced in ES2020, which makes it a relatively new addition to the JavaScript language. For example, the nullish coalescing operator isn't supported in Node.js 12. However, there is a concise alternative with the ternary operator that works in any version of JavaScript.

  5. Nullish coalescing operator (??)

    The nullish coalescing assignment operator (sometimes referred to as the logical nullish assignment operator) will allow you to assign a value to a variable, but only if value of this variable is NULL or undefined, without checking it first. So, before this operator, you could see a piece of code like this:

  6. Advanced JavaScript Operators

    The destructuring assignment is a special operator that allows you to "unpack" or "extract" the values of JavaScript arrays and objects. It has become one of the most useful features of JavaScript language for two reasons: It helps you to avoid code repetition. It keeps your code clean and easy to understand.

  7. JavaScript Nullish Coalescing Operator

    Learn about the JavaScript nullish coalescing operator that accepts two operands and returns the right operand if the left one is null or undefined. ... Why nullish coalescing operator. When assigning a default value to a variable, you often use the ... It only returns the second value when the first one is either null or undefined. The nullish ...

  8. What is the Nullish Coalescing Operator in JavaScript, and how is it useful

    When used in an expression, the Nullish Operator checks the first operand (on the left) to see if its value is null or undefined. If it isn't, the operator returns it from the expression. But if the first operand is any of those values, the operator returns the second operand from the expression. Let's see a quick example:

  9. How the Nullish Coalescing Operator Works in JavaScript

    As the || operator returns the first truthy value, in the above code, the result will be the value stored in value1 which is 1. If value1 is null, undefined, empty or any other falsy value, then the next operand after the || operator will be evaluated and that will the result of the total expression. const value1 = 0; const value2 = 23; const ...

  10. Nullish Coalescing in JavaScript: A Developer's Guide

    Nullish Coalescing in JavaScript offers a robust solution for handling null and undefined values explicitly, allowing for cleaner, more predictable code. By understanding and utilizing this operator, developers can avoid common pitfalls associated with falsy value coercion and ensure their applications handle variable states more gracefully.

  11. Nullish coalescing operator (??)

    The nullish coalescing operator can be seen as a special case of the logical OR ( ||) operator. The latter returns the right-hand side operand if the left operand is any falsy value, not only null or undefined. In other words, if you use || to provide some default value to another variable foo, you may encounter unexpected behaviors if you ...

  12. Nullish Coalescing Assignment Operator in JavaScript

    In JavaScript, dealing with potentially undefined or null values has been a long-standing challenge for developers. We've previously explored the Nullish Coalescing Operator (), a handy tool for ...

  13. Nullish Coalescing Assignment (??=) Operator in JavaScript

    JavaScript Exponentiation Assignment Operator in JavaScript is represented by "**=". This operator is used to raise the value of the variable to the power of the operand which is right. This can also be explained as the first variable is the power of the second operand. The exponentiation operator is equal to Math.pow(). Syntax: a **= b or a = a **

  14. Null Coalescing Operator in JavaScript with ECMAScript 2020

    In case of null values, you'll probably want to return a different result. JavaScript made sure this can be handled with its nullish operator also known as the Null Coalescing Operator, which was added to the language with ECMAScript 2020. With it, you can either return a value or assign it to some other value, depending on a boolean expression.

  15. JavaScript Nullish Coalescing(??) Operator

    The nullish coalescing (??) operator is a logical operator in TypeScript that returns its right-hand side operand if the left-hand side operand is null or undefined; otherwise, it returns the left-hand side operand. This operator is useful for assigning default values to variables, ensuring more consistent and predictable code execution. SyntaxThe

  16. JavaScript Logical Nullish Assignment Operator (??=) Explained

    This post was published 24 Dec, 2021 by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing.

  17. Nullish coalescing · V8

    The JavaScript nullish coalescing operator enables safer default expressions. ... abstract operation. For us regular JavaScript developers, everything is truthy except the falsy values undefined, null, false, 0, NaN ... but still completely valid JavaScript. It uses slightly different semantics, though. Default assignment inside object ...

  18. javascript

    Nullish coalescing operator allows assigning a variable if it's not null or undefined, or an expression otherwise. It is an improvement over previously used || because || will also assign other if b is empty string or other falsy, but not nullish value. However, sometimes, we also use && for value assignment, for example.

  19. javascript

    Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand; OverflowAI GenAI features for Teams; OverflowAPI Train & fine-tune LLMs; Labs The future of collective knowledge sharing; About the company Visit the blog

  20. javascript

    The simplest way I can think of a solution without if is as follows: let iceCream = {. flavor: 'chocolate'. } const foo = 2.5. const bar = undefined; bar && (iceCream.price = bar) // Another possible solution if creating the property with a nullish value is ok for you: iceCream.price = bar || iceCream.price;

  21. javascript

    Here's an example using += in JavaScript (no linter): var a += 42; // ^−−−−−−−− SyntaxError: Unexpected token '+=' console.log(a); In the normal case, you'd just want an assignment operator (ideally using let or const ; var shouldn't be used in new code):