• 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.

In JavaScript, is chained assignment okay?

Am not new to JS or its syntax, but sometimes, the semantics of the language has me stumped at times. At work today, a colleague mentioned this:

is not the same as

since the first version actually assigns the reference to an empty array to a and b. I couldn't quite accept this as true, but I'm not sure. What do you all think?

  • variable-assignment

Daniel Vassallo's user avatar

  • 5 See stackoverflow.com/questions/1758576/… –  Crescent Fresh Commented Aug 2, 2010 at 11:41
  • Thank you, Crescent Fresh - I didn't quite see that question because I was looking for "chained assignment". –  JamieJag Commented Aug 4, 2010 at 13:12
  • Does this answer your question? Multiple left-hand assignment with JavaScript –  ggorlen Commented Jun 3, 2021 at 5:31

7 Answers 7

Yes, they're not the same. var a = b = [] is equivalent to

Not only do both a and b get assigned the same value (a reference to the same empty array), b is not declared at all. In strict mode in ECMAScript 5 and later, this will throw a ReferenceError ; otherwise, unless there is already a variable b in scope, b is silently created as a property of the global object and acts similarly to a global variable, wherever the code is, even inside a function. Which is not good.

You can see this quite easily:

Tim Down's user avatar

  • 3 I didn't see immediately about b being a global variable, thanks! –  JamieJag Commented Aug 4, 2010 at 9:56
  • 5 +1 Another reason to avoid an assignment to an unresolvable reference is that on ES5, under strict mode, a ReferenceError will be thrown. –  Christian C. Salvadó Commented Aug 5, 2010 at 4:18

Your colleague is right:

var a = b = []; a.push('something'); console.log(b); // outputs ["something"]

var a = [], b = []; a.push('something'); console.log(b); // outputs []

DecPK's user avatar

Your colleague is right. The first statement creates a new, empty array. Then, a reference to this array is assigned to b. Then, the same reference (which is the result of the assignment expression) is assigned to a. So a and b refer to the same array.

In all other cases, you create two individual arrays.

By the way: This behavior is quite common and is the same in all C based programming languages. So this is not JavaScript specific.

h2stein's user avatar

  • Thanks for your reply, Tobias, and also for pointing out the commonality in all C-based languages. –  JamieJag Commented Aug 4, 2010 at 9:55
  • This can be tested with arrays in JS: ["dog"] === ["dog"]; returns false, but var a = b = ["dog"]; a === b; returns true. –  b00t Commented Jun 14, 2016 at 22:01

With the first example b is a reference to a , and b becomes a global variable, accessible from anywhere (and it replaces any b variable that may already exist in the global scope).

Fabien Ménager's user avatar

To complement the already provided answers. ref assignments are different from value assignments

Now that we've addressed 2 two, your question also makes reference to linting, which is the practice of "pretty code" (not functional). In fact, JSHint has deprecated all their "pretty code rules"

That been said, I usually use the following style.-

percebus's user avatar

To accomplish this, you need to split the var declaration from the chained assignment (see: http://davidshariff.com/blog/chaining-variable-assignments-in-javascript-words-of-caution/ ).

But if you do as you described ( var one = two = 3; in this example) two leaks into the global space, while one is declared in the local scope.

Campbeln's user avatar

Since your question is if it's ok or not, it's ok except in strict mode. Modules are in strict mode by default, so it's not allowed.

Jonathan's user avatar

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 object variable-assignment or ask your own question .

  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Introducing an accessibility dashboard and some upcoming changes to display...
  • Tag hover experiment wrap-up and next steps

Hot Network Questions

  • When can a citizen's arrest of an Interpol fugitive be legal in Washington D.C.?
  • Is there mutable aliasing in this list of variable references?
  • Why isn't the Liar's Paradox just accepted to be complete nonsense?
  • In Norway, when number ranges are listed 3 times on a sign, what do they mean?
  • How much does flight help the ranger?
  • How do I rigorously compute probabilities over infinite sequences of coin flips?
  • Inverse relationship between Stirling numbers of the first and second kind via generating functions
  • On the use of overtly
  • Short story probably in Omni magazine in the 1980s set in a cyberpunk bar… but it's 1899 or so
  • Operator-precedence calculator in C
  • dealing with the feeling after rejection
  • What was R' Chanina's Technique to Revive R' Yochanan?
  • How would a creature adverse to solar energy (ie, a wraith) get energy and what would it do with it?
  • How many kinds of contradictions are there?
  • How to prevent ambiguity that arises from multiple conditional statements in one sentence?
  • If pressure is caused by the weight of water above you, why is pressure said to act in all direction, not just down?
  • What is the first recorded usage of the three ‘’R’s: Reading wRiting and aRithmetic?"
  • Why don't programming languages or IDEs support attaching descriptive metadata to variables?
  • Why is the completely dark disk of the Moon visible on a new moon if the lunar orbit is at an angle to the Earth’s?
  • Why do most published papers hit the maximum page limit exactly?
  • Self-employed health insurance deduction and insurance just for my kids
  • Simplifing equation with complex coefficients
  • SSH connectivity issues between local server and remote server
  • Remove the Freehub Body from a Omnium Cargo Bike

js chain assignment

  • Getting started with JavaScript
  • Awesome Book
  • Awesome Community
  • Awesome Course
  • Awesome Tutorial
  • Awesome YouTube
  • .postMessage() and MessageEvent
  • Anti-patterns
  • Chaining assignments in var declarations.
  • Arithmetic (Math)
  • Arrow Functions
  • Async functions (async/await)
  • Async Iterators
  • Automatic Semicolon Insertion - ASI
  • Battery Status API
  • Behavioral Design Patterns
  • Binary Data
  • Bitwise operators
  • Bitwise Operators - Real World Examples (snippets)
  • BOM (Browser Object Model)
  • Built-in Constants
  • Comparison Operations
  • Constructor functions
  • Context (this)
  • Creational Design Patterns
  • Custom Elements
  • Data attributes
  • Data Manipulation
  • Datatypes in Javascript
  • Date Comparison
  • Declarations and Assignments
  • Destructuring assignment
  • Detecting browser
  • Enumerations
  • Error Handling
  • Escape Sequences
  • Evaluating JavaScript
  • execCommand and contenteditable
  • File API, Blobs and FileReaders
  • Functional JavaScript
  • Geolocation
  • Global error handling in browsers
  • How to make iterator usable inside async callback function
  • Inheritance
  • Intervals and Timeouts
  • JavaScript Variables
  • Linters - Ensuring code quality
  • Localization
  • Memory efficiency
  • Method Chaining
  • Modals - Prompts
  • Modularization Techniques
  • Namespacing
  • Navigator Object
  • Notifications API
  • Performance Tips
  • Prototypes, objects
  • Regular expressions
  • requestAnimationFrame
  • Reserved Keywords
  • Same Origin Policy & Cross-Origin Communication
  • Security issues
  • Selection API
  • Server-sent events
  • Setters and Getters
  • Strict mode
  • Tail Call Optimization
  • Template Literals
  • The Event Loop
  • Transpiling
  • Unary Operators
  • Unit Testing Javascript
  • Using javascript to get/set CSS custom variables
  • Variable coercion/conversion
  • Vibration API
  • Web Cryptography API
  • Web Storage

JavaScript Anti-patterns Chaining assignments in var declarations.

Fastest entity framework extensions.

Chaining assignments as part of a var declaration will create global variables unintentionally.

For example:

Will result in:

In the above example, a is local but b becomes global. This is because of the right to left evaluation of the = operator. So the above code actually evaluated as

The correct way to chain var assignments is:

This will make sure that both a and b will be local variables.

Got any JavaScript Question?

pdf

  • Advertise with us
  • Cookie Policy
  • Privacy Policy

Get monthly updates about new articles, cheatsheets, and tricks.

Advanced JavaScript Operators – Nullish Coalescing, Optional Chaining, and Destructuring Assignment

Nathan Sebhastian

Hi Everyone! In this article, I'm going to teach you how to use three advanced JavaScript operators: the Nullish Coalescing, Optional Chaining, and Destructuring Assignment operators.

These three operators will help you write clearer and less error-prone code.

The Nullish Coalescing Operator

When you’re inspecting JavaScript code, you may find an expression using a double question mark ( ?? ), as in the code below:

The double question mark is a logical operator that returns the expression on the right-hand side of the mark when the expression on the left-hand side is null or undefined

This operator is also known as the nullish coalescing operator. It’s a new feature introduced in JavaScript ES2020 that allows you to check for null or undefined values in a more concise way.

Nullish Coalescing Operator Syntax

The syntax for the nullish coalescing operator is very simple. It consists of two question marks ?? placed between two operands.

Here’s an example:

The code above assigns the firstName variable value as the value of the username variable.

When the firstName value is null or undefined , then the value Guest will be assigned to the username variable instead:

nullish-coalescing-output

You can also write it this way:

As you can see, you don’t need an if-else statement to check for null or undefined values.

Why JavaScript Needs This Operator

The nullish coalescing operator was created as an improved alternative to the OR operator || .

The OR operator was originally created to provide a default or fallback value when the left-hand expression is falsy, or evaluates to false .

But after some real-world uses, it’s clear that there are times when developers want to return values that are considered falsy, such as 0 and an empty string ( "" )

The use of the OR operator will prevent you from returning any falsy values at all. Consider the following example:

By using the nullish coalescing operator, you will only replace exactly null and undefined values with the right-hand value.

The nullish coalescing operator can be used with any type of value, including numbers, strings, and objects.

Nullish Coalescing Operator Use Cases

The nullish coalescing operator is useful in a variety of situations where you need to check for null or undefined values and provide a default value.

Here are several examples of common use cases:

Handling Missing Function Arguments

When a function is called, it’s possible that some of the arguments may be omitted.

The Nullish Coalescing Operator can be used to provide default values for a missing argument as follows:

Accessing Object Properties

When working with objects, it’s possible that a property may not exist or is undefined .

The Nullish Coalescing Operator can be used to safely access object properties and provide a default value when the property is missing:

Choosing Between a Variable and a Constant

You may want to select a value from a variable or a constant if the variable is null or undefined :

As you can see, the Nullish Coalescing Operator is a great feature that can make your code more concise and reliable.

Using ?? with the || and && Operators

For safety reasons, the double question mark can’t be used together with JavaScript OR ( || ) and AND ( && ) operators without parentheses () separating the operators.

For example, the following code tries to see if either firstName or lastName variable can be used as the value of username before using "Guest" as its value:

This is because JavaScript won’t be able to determine which operator it needs to evaluate first. You need to use parentheses to clearly indicate the priority of the evaluations.

The following code will first evaluate the expressions inside the parentheses:

And that’s how you combine the nullish coalescing operator with either AND or OR operator.

The Optional Chaining Operator

Like the nullish coalescing operator, the optional chaining operator is a modern addition to JavaScript that offers a better way to do things.

The optional chaining operator ?. gives you a safe way to access properties and methods of an object, avoiding an error in the process.

One of the most common problems in JavaScript is that you can get an error when you access a property of an undefined value.

For example, suppose you have a car object as follows:

In the example above, accessing the manufacturer property returns undefined , but when you try to access the address property of the manufacturer property, JavaScript returns an error.

Even though this is how JavaScript works, a better way to handle the non-existent property would be to just return an undefined back, just like when we try to access the manufacturer property.

This is why the optional chaining operator was created. The operator returns either the value of the property, or undefined when the property is null or undefined .

To use the operator, just add a question mark in front of the dot . notation:

The optional chaining operator can be added anytime you use the dot notation to access a property or method.

This operator allows you to avoid the TypeError that occurs when accessing a property or calling a method from a non-existent property:

Note that the optional chaining operator only checks the value before it. If the car variable can be null , then you need to add the operator after when accessing the car object as well.

See the following example:

And that’s how the optional chaining operator works. It’s really useful when you’re working with objects in your project.

Next, let’s learn about the destructuring assignment.

Destructuring Assignment Operator

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.

Let’s see how you can destructure an array and an object next.

Destructuring Arrays

Here’s how you normally assign an array values to variables:

The code above works, but you need two lines of code to get two elements from an array. Using the destructuring assignment, you can assign array elements into variables in one short line:

The above code will return the same value for firstIndex and secondIndex variable. No matter how many elements you have, the destructuring will start from the zero index.

To create a destructuring assignment, you need to add square brackets [] after the let / const keyword. When you add square brackets after the assignment ( = ) operator, it’s an array. If you add them before the assignment operator, it’s a destructuring assignment.

You can also use the rest operator …​ to copy the rest of the values after your assignment. Take a look at the following example:

The rest variable will contain an array with values of ['Jack','Aston'] .

You can also put default values for these variables when the extracted value is undefined:

You can also immediately assign the return of a function into assignments. This is frequently used in libraries like React:

The variable a will return "John" and b will return "Jack".

Finally, you can also ignore some variables by skipping the assignment for that index:

Destructuring assignment makes unpacking array values easier and shorter, with less repetition.

Optional chaining (?.)

The optional chaining ( ?. ) operator accesses an object's property or calls a function. If the object accessed or function called using this operator is undefined or null , the expression short circuits and evaluates to undefined instead of throwing an error.

Description

The ?. operator is like the . chaining operator, except that instead of causing an error if a reference is nullish ( null or undefined ), the expression short-circuits with a return value of undefined . When used with function calls, it returns undefined if the given function does not exist.

This results in shorter and simpler expressions when accessing chained properties when the possibility exists that a reference may be missing. It can also be helpful while exploring the content of an object when there's no known guarantee as to which properties are required.

For example, consider an object obj which has a nested structure. Without optional chaining, looking up a deeply-nested subproperty requires validating the references in between, such as:

The value of obj.first is confirmed to be non- null (and non- undefined ) before accessing the value of obj.first.second . This prevents the error that would occur if you accessed obj.first.second directly without testing obj.first .

This is an idiomatic pattern in JavaScript, but it gets verbose when the chain is long, and it's not safe. For example, if obj.first is a Falsy value that's not null or undefined , such as 0 , it would still short-circuit and make nestedProp become 0 , which may not be desirable.

With the optional chaining operator ( ?. ), however, you don't have to explicitly test and short-circuit based on the state of obj.first before trying to access obj.first.second :

By using the ?. operator instead of just . , JavaScript knows to implicitly check to be sure obj.first is not null or undefined before attempting to access obj.first.second . If obj.first is null or undefined , the expression automatically short-circuits, returning undefined .

This is equivalent to the following, except that the temporary variable is in fact not created:

Optional chaining cannot be used on a non-declared root object, but can be used with a root object with value undefined .

Optional chaining with function calls

You can use optional chaining when attempting to call a method which may not exist. This can be helpful, for example, when using an API in which a method might be unavailable, either due to the age of the implementation or because of a feature which isn't available on the user's device.

Using optional chaining with function calls causes the expression to automatically return undefined instead of throwing an exception if the method isn't found:

However, if there is a property with such a name which is not a function, using ?. will still raise a TypeError exception "someInterface.customMethod is not a function".

Note: If someInterface itself is null or undefined , a TypeError exception will still be raised ("someInterface is null"). If you expect that someInterface itself may be null or undefined , you have to use ?. at this position as well: someInterface?.customMethod?.() .

eval?.() is the shortest way to enter indirect eval mode.

Optional chaining with expressions

You can also use the optional chaining operator with bracket notation , which allows passing an expression as the property name:

This is particularly useful for arrays, since array indices must be accessed with square brackets.

Invalid optional chaining

It is invalid to try to assign to the result of an optional chaining expression:

Template literal tags cannot be an optional chain (see SyntaxError: tagged template cannot be used with optional chain ):

The constructor of new expressions cannot be an optional chain (see SyntaxError: new keyword cannot be used with an optional chain ):

Short-circuiting

When using optional chaining with expressions, if the left operand is null or undefined , the expression will not be evaluated. For instance:

Subsequent property accesses will not be evaluated either.

This is equivalent to:

However, this short-circuiting behavior only happens along one continuous "chain" of property accesses. If you group one part of the chain, then subsequent property accesses will still be evaluated.

Except the temp variable isn't created.

Basic example

This example looks for the value of the name property for the member bar in a map when there is no such member. The result is therefore undefined .

Dealing with optional callbacks or event handlers

If you use callbacks or fetch methods from an object with a destructuring assignment , you may have non-existent values that you cannot call as functions unless you have tested their existence. Using ?. , you can avoid this extra test:

Stacking the optional chaining operator

With nested structures, it is possible to use optional chaining multiple times:

Combining with the nullish coalescing operator

The nullish coalescing operator may be used after optional chaining in order to build a default value when none was found:

Specifications

Specification

Browser compatibility

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

  • Nullish coalescing operator ( ?? )
  • DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter

Method Chaining in JavaScript

As a good programming practice, we should write individual functions/methods for dealing with individual actions. And, writing only one method/function for all actions is a thing. However, sticking to good practice takes a toll on the readability and comprehensibility of the code, because defining a separate function for each action means that the output of a single function/method is input. This makes code comprehensibility even worse, as the function needs to be nested in reverse order. This is where method chaining comes to the rescue.

What is Method chaining?

It is a programming strategy that simplifies and embellishes your code. It is a mechanism for calling a method on another method of the same object.

JavaScript this keyword refers to the current object in which it is called. Thus, when a method returns this , it simply returns an instance of the object in which it is returned. Since the returned value is an instance of an object, it is, therefore, possible to call another method of an object to the returned value, which is its instance. This makes method chaining possible in JavaScript.

Example 1: In this example, each method in Land.prototype returns this , which refers to the entire instance of that Land object. This would help in calling a method on another method of the same object.

Example 2: In this example, we will chain the inbuilt methods of the String

Please Login to comment...

Similar reads.

  • Web Technologies

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. JavaScript Chain Functions Examples

    js chain assignment

  2. JavaScript Prototype Chains, Scope Chains, and Performance: What You

    js chain assignment

  3. Understanding JavaScript's Prototype-Based Inheritance

    js chain assignment

  4. NodeJS : JS

    js chain assignment

  5. Scope Chain in javascript

    js chain assignment

  6. Understanding of JS prototype chains

    js chain assignment

COMMENTS

  1. In JavaScript, is chained assignment okay? - Stack Overflow

    Yes, they're not the same. var a = b = [] is equivalent to. var a; b = []; a = b; Not only do both a and b get assigned the same value (a reference to the same empty array), b is not declared at all.

  2. Assignment (=) - JavaScript | MDN - MDN Web Docs

    The assignment (=) operator is used to assign a value to a variable or property. The assignment expression itself has a value, which is the assigned value. This allows multiple assignments to be chained in order to assign a single value to multiple variables.

  3. JavaScript Tutorial => Chaining assignments in var declarations.

    The correct way to chain var assignments is: var a, b; a = b = 0; Or: var a = 0, b = a; This will make sure that both a and b will be local variables.

  4. Optional chaining - The Modern JavaScript Tutorial

    The optional chaining ?. has no use on the left side of an assignment. For example: let user = null; user?.name = "John"; // Error, doesn't work // because it evaluates to: undefined = "John"

  5. How to Use Chaining in JavaScript Like a Pro | by Michael ...

    Method chaining, or simply chaining, in JavaScript can be defined as when one or more sequential methods get invoked from an object without the introduction of unnecessary variables. The sole purpose of chaining is to make our code more readable and reduce the redundancy within.

  6. Advanced JavaScript Operators – Nullish Coalescing, Optional ...

    In this article, I'm going to teach you how to use three advanced JavaScript operators: the Nullish Coalescing, Optional Chaining, and Destructuring Assignment operators. These three operators will help you write clearer and less error-prone code.

  7. Chaining - The Modern JavaScript Tutorial

    Modify the code of up, down, and showStep to make the calls chainable, like this: ladder.up().up().down().showStep().down().showStep(); // shows 1 then 0. Such an approach is widely used across JavaScript libraries. Open a sandbox with tests. solution.

  8. Chaining Patterns in JavaScript. Chain your way to success ...

    This post will go over different chaining patterns in JavaScript and I hope that this will help you in any way possible when it comes to writing your chaining operations. Method Chaining. In JavaScript, method chaining is when methods are invoked from one object to another without creating intermediate variables.

  9. Optional chaining (?.) - JavaScript | MDN - MDN Web Docs">Optional chaining (?.) - JavaScript | MDN - MDN Web Docs

    You can use optional chaining when attempting to call a method which may not exist. This can be helpful, for example, when using an API in which a method might be unavailable, either due to the age of the implementation or because of a feature which isn't available on the user's device. Using optional chaining with function calls causes the ...

  10. Method Chaining in JavaScript - GeeksforGeeks">Method Chaining in JavaScript - GeeksforGeeks

    With jQuery, we can use do chaining which means to chain together multiple methods in a single statement on a single element. We have been using a single statement at once, but now using the chaining method we can bind multiple methods to make the code short.