Object.assign() in JavaScript

In JavaScript, the Object.assign() function copies properties from one or more source objects to a target object. It returns the target object.

Object.assign() is commonly used to shallow copy objects, although the spread operator is generally faster than Object.assign() for shallow copying . Shallow copying is most commonly used in Redux reducers .

Multiple Sources

You can pass multiple source objects to Object.assign() . If there's multiple sources with the same property, the last one in the parameter list wins out.

More Fundamentals Tutorials

  • Check if a Date is Valid in JavaScript
  • Encode base64 in JavaScript
  • Check if URL Contains a String
  • JavaScript Add Month to Date
  • JavaScript Add Days to Date
  • 3 Patterns to Merge Arrays in JavaScript
  • Convert a BigInt to a Number in JavaScript

Understanding Object.assign() Method in JavaScript

Cloning an object, merging objects, converting an array to an object, browser compatibility.

The Object.assign() method was introduced in ES6 that copies all enumerable own properties from one or more source objects to a target object, and returns the target object .

The Object.assign() method invokes the getters on the source objects and setters on the target object. It assigns properties only, not copying or defining new properties.

The properties in the target object are overwritten by the properties in source objects if they have the same key. Similarly, the later source objects' properties are overwritten by the earlier ones.

The Object.assign() method handles null and undefined source values gracefully, and doesn't throw any exception.

Here is how the syntax of Object.assign() looks like:

  • target — The target object that is modified and returned after applying the sources' properties.
  • sources — The source object(s) containing the properties you want to apply to the target object.

The Object.assign() method is one of the four ways, I explained earlier, to clone an object in JavaScript.

The following example demonstrates how you can use Object.assign() to clone an object:

Remember that Object.assign() only creates a shallow clone of the object and not a deep clone.

To create a deep clone, you can either use JSON methods or a 3rd-party library like Lodash .

The Object.assign() method can also merge multiple source objects into a target object. If you do not want to modify the target object, just pass an empty ( {} ) object as target as shown below:

If the source objects have same properties , they are overwritten by the properties of the objects later in the parameters order:

Lastly, you could also use the Object.assign() method to convert an array to an object in JavaScript. The array indexes are converted to object keys, and array values are converted to object values:

As Object.assign() is part of ES6, it only works in modern browsers. To support older browsers like IE, you can use a polyfill available on MDN.

To learn more about JavaScript objects, prototypes, and classes, take a look at this guide .

Read Next: Understanding Array.from() Method in JavaScript

✌️ Like this article? Follow me on Twitter and LinkedIn . You can also subscribe to RSS Feed .

You might also like...

  • Get the length of a Map in JavaScript
  • Delete an element from a Map in JavaScript
  • Get the first element of a Map in JavaScript
  • Get an element from a Map using JavaScript
  • Update an element in a Map using JavaScript
  • Add an element to a Map in JavaScript

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.

  • JavaScript, Node.js & Spring Boot
  • In-depth tutorials
  • Super-handy protips
  • Cool stuff around the web
  • 1-click unsubscribe
  • No spam, free-forever!
  • Skip to main content
  • Select language
  • Skip to search
  • Object.assign()

Return value

Copying accessors.

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

The target object.

Description

Properties in the target object will be overwritten by properties in the sources if they have the same key.  Later sources' properties will similarly overwrite earlier ones.  

The Object.assign() method only copies enumerable and own properties from a source object to a target object. It uses [[Get]] on the source and [[Set]] on the target, so it will invoke getters and setters. Therefore it assigns properties versus just copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters. For copying property definitions, including their enumerability, into prototypes Object.getOwnPropertyDescriptor() and Object.defineProperty() should be used instead.

Both String and Symbol properties are copied.

In case of an error, for example if a property is non-writable, a TypeError will be raised, and the target object can be changed if any properties are added before error is raised.

Note that Object.assign() does not throw on null or undefined source values.

Cloning an object

Warning for deep clone.

For deep cloning, we need to use other alternatives because Object.assign() copies property values. If the source value is a reference to an object, it only copies that reference value.

Merging objects

Merging objects with same properties.

The properties are overwritten by other objects that have the same properties later in the parameters order.

Copying symbol-typed properties

Properties on the prototype chain and non-enumerable properties cannot be copied, primitives will be wrapped to objects, exceptions will interrupt the ongoing copying task.

This polyfill doesn't support symbol properties, since ES5 doesn't have symbols anyway:

Specifications

Browser compatibility.

  • Object.defineProperties()
  • Enumerability and ownership of properties

Document Tags and Contributors

  • ECMAScript 2015
  • Standard built-in objects
  • Object.prototype
  • Object.prototype.__count__
  • Object.prototype.__noSuchMethod__
  • Object.prototype.__parent__
  • Object.prototype.__proto__
  • Object.prototype.constructor
  • Object.create()
  • Object.defineProperty()
  • Object.entries()
  • Object.freeze()
  • Object.getNotifier()
  • Object.getOwnPropertyDescriptor()
  • Object.getOwnPropertyDescriptors()
  • Object.getOwnPropertyNames()
  • Object.getOwnPropertySymbols()
  • Object.getPrototypeOf()
  • Object.is()
  • Object.isExtensible()
  • Object.isFrozen()
  • Object.isSealed()
  • Object.keys()
  • Object.observe()
  • Object.preventExtensions()
  • Object.prototype.__defineGetter__()
  • Object.prototype.__defineSetter__()
  • Object.prototype.__lookupGetter__()
  • Object.prototype.__lookupSetter__()
  • Object.prototype.eval()
  • Object.prototype.hasOwnProperty()
  • Object.prototype.isPrototypeOf()
  • Object.prototype.propertyIsEnumerable()
  • Object.prototype.toLocaleString()
  • Object.prototype.toSource()
  • Object.prototype.toString()
  • Object.prototype.unwatch()
  • Object.prototype.valueOf()
  • Object.prototype.watch()
  • Object.seal()
  • Object.setPrototypeOf()
  • Object.unobserve()
  • Object.values()
  • Inheritance:
  • Function.arguments
  • Function.arity
  • Function.caller
  • Function.displayName
  • Function.length
  • Function.name
  • Function.prototype
  • Function.prototype.apply()
  • Function.prototype.bind()
  • Function.prototype.call()
  • Function.prototype.isGenerator()
  • Function.prototype.toSource()
  • Function.prototype.toString()

Understanding Object.assign() in JavaScript – A Complete Guide and Examples

Related posts:.

  • Demystifying the Java Spread Operator – A Comprehensive Guide for Developers
  • Unlocking the Power of C# Spread Operator – A Comprehensive Guide
  • Mastering JavaScript Three Dots – A Comprehensive Guide to Understanding Spread and Rest Operators
  • Mastering Object.assign() in JavaScript – A Comprehensive Guide for Efficiently Assigning Objects
  • The Power of TypeScript’s Three Dots – Exploring Spread and Rest Operators in Depth

javascript multiple assignment from object

Darren Jones

A Guide to Variable Assignment and Mutation in JavaScript

Share this article

A Guide to Variable Assignment and Mutation in JavaScript

Variable Assignment

Variable reassignment, variable assignment by reference, copying by reference, the spread operator to the rescue, are mutations bad, frequently asked questions (faqs) about javascript variable assignment and mutation.

Mutations are something you hear about fairly often in the world of JavaScript, but what exactly are they, and are they as evil as they’re made out to be?

In this article, we’re going to cover the concepts of variable assignment and mutation and see why — together — they can be a real pain for developers. We’ll look at how to manage them to avoid problems, how to use as few as possible, and how to keep your code predictable.

If you’d like to explore this topic in greater detail, or get up to speed with modern JavaScript, check out the first chapter of my new book Learn to Code with JavaScript for free.

Let’s start by going back to the very basics of value types …

Every value in JavaScript is either a primitive value or an object. There are seven different primitive data types:

  • numbers, such as 3 , 0 , -4 , 0.625
  • strings, such as 'Hello' , "World" , `Hi` , ''
  • Booleans, true and false
  • symbols — a unique token that’s guaranteed never to clash with another symbol
  • BigInt — for dealing with large integer values

Anything that isn’t a primitive value is an object , including arrays, dates, regular expressions and, of course, object literals. Functions are a special type of object. They are definitely objects, since they have properties and methods, but they’re also able to be called.

Variable assignment is one of the first things you learn in coding. For example, this is how we would assign the number 3 to the variable bears :

A common metaphor for variables is one of boxes with labels that have values placed inside them. The example above would be portrayed as a box containing the label “bears” with the value of 3 placed inside.

variables like a box

An alternative way of thinking about what happens is as a reference, that maps the label bears to the value of 3 :

variables like a reference

If I assign the number 3 to another variable, it’s referencing the same value as bears:

variables referencing the same value

The variables bears and musketeers both reference the same primitive value of 3. We can verify this using the strict equality operator, === :

The equality operator returns true if both variables are referencing the same value.

Some gotchas when working with objects

The previous examples showed primitive values being assigned to variables. The same process is used when assigning objects:

This assignment means that the variable ghostbusters references an object:

variables referencing different objects

A big difference when assigning objects to variables, however, is that if you assign another object literal to another variable, it will reference a completely different object — even if both object literals look exactly the same! For example, the assignment below looks like the variable tmnt (Teenage Mutant Ninja Turtles) references the same object as the variable ghostbusters :

Even though the variables ghostbusters and tmnt look like they reference the same object, they actually both reference a completely different object, as we can see if we check with the strict equality operator:

variables referencing different objects

When the const keyword was introduced in ES6, many people mistakenly believed that constants had been introduced to JavaScript, but this wasn’t the case. The name of this keyword is a little misleading.

Any variable declared with const can’t be reassigned to another value. This goes for primitive values and objects. For example, the variable bears was declared using const in the previous section, so it can’t have another value assigned to it. If we try to assign the number 2 to the variable bears , we get an error:

The reference to the number 3 is fixed and the bears variable can’t be reassigned another value.

The same applies to objects. If we try to assign a different object to the variable ghostbusters , we get the same error:

Variable reassignment using let

When the keyword let is used to declare a variable, it can be reassigned to reference a different value later on in our code. For example, we declared the variable musketeers using let , so we can change the value that musketeers references. If D’Artagnan joined the Musketeers, their number would increase to 4:

variables referencing different values

This can be done because let was used to declare the variable. We can alter the value that musketeers references as many times as we like.

The variable tmnt was also declared using let , so it can also be reassigned to reference another object (or a different type entirely if we like):

Note that the variable tmnt now references a completely different object ; we haven’t just changed the number property to 5.

In summary , if you declare a variable using const , its value can’t be reassigned and will always reference the same primitive value or object that it was originally assigned to. If you declare a variable using let , its value can be reassigned as many times as required later in the program.

Using const as often as possible is generally considered good practice, as it means that the value of variables remains constant and the code is more consistent and predictable, making it less prone to errors and bugs.

In native JavaScript, you can only assign values to variables. You can’t assign variables to reference another variable, even though it looks like you can. For example, the number of Stooges is the same as the number of Musketeers, so we can assign the variable stooges to reference the same value as the variable musketeers using the following:

This looks like the variable stooges is referencing the variable musketeers , as shown in the diagram below:

variables cannot reference another variable

However, this is impossible in native JavaScript: a variable can only reference an actual value; it can’t reference another variable . What actually happens when you make an assignment like this is that the variable on the left of the assignment will reference the value the variable on the right references, so the variable stooges will reference the same value as the musketeers variable, which is the number 3. Once this assignment has been made, the stooges variable isn’t connected to the musketeers variable at all.

variables referencing values

This means that if D’Artagnan joins the Musketeers and we set the value of the musketeers to 4, the value of stooges will remain as 3. In fact, because we declared the stooges variable using const , we can’t set it to any new value; it will always be 3.

In summary : if you declare a variable using const and set it to a primitive value, even via a reference to another variable, then its value can’t change. This is good for your code, as it means it will be more consistent and predictable.

A value is said to be mutable if it can be changed. That’s all there is to it: a mutation is the act of changing the properties of a value.

All primitive value in JavaScript are immutable : you can’t change their properties — ever. For example, if we assign the string "cake" to variable food , we can see that we can’t change any of its properties:

If we try to change the first letter to “f”, it looks like it has changed:

But if we take a look at the value of the variable, we see that nothing has actually changed:

The same thing happens if we try to change the length property:

Despite the return value implying that the length property has been changed, a quick check shows that it hasn’t:

Note that this has nothing to do with declaring the variable using const instead of let . If we had used let , we could set food to reference another string, but we can’t change any of its properties. It’s impossible to change any properties of primitive data types because they’re immutable .

Mutability and objects in JavaScript

Conversely, all objects in JavaScript are mutable, which means that their properties can be changed, even if they’re declared using const (remember let and const only control whether or not a variable can be reassigned and have nothing to do with mutability). For example, we can change the the first item of an array using the following code:

Note that this change still occurred, despite the fact that we declared the variable food using const . This shows that using const does not stop objects from being mutated .

We can also change the length property of an array, even if it has been declared using const :

Remember that when we assign variables to object literals, the variables will reference completely different objects, even if they look the same:

But if we assign a variable fantastic4 to another variable, they will both reference the same object:

This assigns the variable fantastic4 to reference the same object that the variable tmnt references, rather than a completely different object.

variables referencing the same object

This is often referred to as copying by reference , because both variables are assigned to reference the same object.

This is important, because any mutations made to this object will be seen in both variables.

So, if Spider-Man joins The Fantastic Four, we might update the number value in the object:

This is a mutation, because we’ve changed the number property rather than setting fantastic4 to reference a new object.

This causes us a problem, because the number property of tmnt will also also change, possibly without us even realizing:

This is because both tmnt and fantastic4 are referencing the same object, so any mutations that are made to either tmnt or fantastic4 will affect both of them.

This highlights an important concept in JavaScript: when objects are copied by reference and subsequently mutated, the mutation will affect any other variables that reference that object. This can lead to unintended side effects and bugs that are difficult to track down.

So how do you make a copy of an object without creating a reference to the original object? The answer is to use the spread operator !

The spread operator was introduced for arrays and strings in ES2015 and for objects in ES2018. It allows you to easily make a shallow copy of an object without creating a reference to the original object.

The example below shows how we could set the variable fantastic4 to reference a copy of the tmnt object. This copy will be exactly the same as the tmnt object, but fantastic4 will reference a completely new object. This is done by placing the name of the variable to be copied inside an object literal with the spread operator in front of it:

What we’ve actually done here is assign the variable fantastic4 to a new object literal and then used the spread operator to copy all the enumerable properties of the object referenced by the tmnt variable. Because these properties are values, they’re copied into the fantastic4 object by value, rather than by reference.

variables referencing different objects

Now any changes that are made to either object won’t affect the other. For example, if we update the number property of the fantastic4 variable to 5, it won’t affect the tmnt variable:

Changes don't affect the other object

The spread operator also has a useful shortcut notation that can be used to make copies of an object and then make some changes to the new object in a single line of code.

For example, say we wanted to create an object to model the Teenage Mutant Ninja Turtles. We could create the first turtle object, and assign the variable leonardo to it:

The other turtles all have the same properties, except for the weapon and color properties, that are different for each turtle. It makes sense to make a copy of the object that leonardo references, using the spread operator, and then change the weapon and color properties, like so:

We can do this in one line by adding the properties we want to change after the reference to the spread object. Here’s the code to create new objects for the variables donatello and raphael :

Note that using the spread operator in this way only makes a shallow copy of an object. To make a deep copy, you’d have to do this recursively, or use a library. Personally, I’d advise that you try to keep your objects as shallow as possible.

In this article, we’ve covered the concepts of variable assignment and mutation and seen why — together — they can be a real pain for developers.

Mutations have a bad reputation, but they’re not necessarily bad in themselves. In fact, if you’re building a dynamic web app, it must change at some point. That’s literally the meaning of the word “dynamic”! This means that there will have to be some mutations somewhere in your code. Having said that, the fewer mutations there are, the more predictable your code will be, making it easier to maintain and less likely to develop any bugs.

A particularly toxic combination is copying by reference and mutations. This can lead to side effects and bugs that you don’t even realize have happened. If you mutate an object that’s referenced by another variable in your code, it can cause lots of problems that can be difficult to track down. The key is to try and minimize your use of mutations to the essential and keep track of which objects have been mutated.

In functional programming, a pure function is one that doesn’t cause any side effects, and mutations are one of the biggest causes of side effects.

A golden rule is to avoid copying any objects by reference. If you want to copy another object, use the spread operator and then make any mutations immediately after making the copy.

Next up, we’ll look into array mutations in JavaScript .

Don’t forget to check out my new book Learn to Code with JavaScript if you want to get up to speed with modern JavaScript. You can read the first chapter for free. And please reach out on Twitter if you have any questions or comments!

What is the difference between variable assignment and mutation in JavaScript?

In JavaScript, variable assignment refers to the process of assigning a value to a variable. For example, let x = 5; Here, we are assigning the value 5 to the variable x. On the other hand, mutation refers to the process of changing the value of an existing variable. For example, if we later write x = 10; we are mutating the variable x by changing its value from 5 to 10.

How does JavaScript handle variable assignment and mutation differently for primitive and non-primitive data types?

JavaScript treats primitive data types (like numbers, strings, and booleans) and non-primitive data types (like objects and arrays) differently when it comes to variable assignment and mutation. For primitive data types, when you assign a variable, a copy of the value is created and stored in a new memory location. However, for non-primitive data types, when you assign a variable, both variables point to the same memory location. Therefore, if you mutate one variable, the change is reflected in all variables that point to that memory location.

What is the concept of pass-by-value and pass-by-reference in JavaScript?

Pass-by-value and pass-by-reference are two ways that JavaScript can pass variables to a function. When JavaScript passes a variable by value, it creates a copy of the variable’s value and passes that copy to the function. Any changes made to the variable inside the function do not affect the original variable. However, when JavaScript passes a variable by reference, it passes a reference to the variable’s memory location. Therefore, any changes made to the variable inside the function also affect the original variable.

How can I prevent mutation in JavaScript?

There are several ways to prevent mutation in JavaScript. One way is to use the Object.freeze() method, which prevents new properties from being added to an object, existing properties from being removed, and prevents changing the enumerability, configurability, or writability of existing properties. Another way is to use the const keyword when declaring a variable. This prevents reassignment of the variable, but it does not prevent mutation of the variable’s value if the value is an object or an array.

What is the difference between shallow copy and deep copy in JavaScript?

In JavaScript, a shallow copy of an object is a copy of the object where the values of the original object and the copy point to the same memory location for non-primitive data types. Therefore, if you mutate the copy, the original object is also mutated. On the other hand, a deep copy of an object is a copy of the object where the values of the original object and the copy do not point to the same memory location. Therefore, if you mutate the copy, the original object is not mutated.

How can I create a deep copy of an object in JavaScript?

One way to create a deep copy of an object in JavaScript is to use the JSON.parse() and JSON.stringify() methods. The JSON.stringify() method converts the object into a JSON string, and the JSON.parse() method converts the JSON string back into an object. This creates a new object that is a deep copy of the original object.

What is the MutationObserver API in JavaScript?

The MutationObserver API provides developers with a way to react to changes in a DOM. It is designed to provide a general, efficient, and robust API for reacting to changes in a document.

How does JavaScript handle variable assignment and mutation in the context of closures?

In JavaScript, a closure is a function that has access to its own scope, the scope of the outer function, and the global scope. When a variable is assigned or mutated inside a closure, it can affect the value of the variable in the outer scope, depending on whether the variable was declared in the closure’s scope or the outer scope.

What is the difference between var, let, and const in JavaScript?

In JavaScript, var, let, and const are used to declare variables. var is function scoped, and if it is declared outside a function, it is globally scoped. let and const are block scoped, meaning they exist only within the block they are declared in. The difference between let and const is that let allows reassignment, while const does not.

How does JavaScript handle variable assignment and mutation in the context of asynchronous programming?

In JavaScript, asynchronous programming allows multiple things to happen at the same time. When a variable is assigned or mutated in an asynchronous function, it can lead to unexpected results if other parts of the code are relying on the value of the variable. This is because the variable assignment or mutation may not have completed before the other parts of the code run. To handle this, JavaScript provides several features, such as promises and async/await, to help manage asynchronous code.

Darren loves building web apps and coding in JavaScript, Haskell and Ruby. He is the author of Learn to Code using JavaScript , JavaScript: Novice to Ninja and Jump Start Sinatra .He is also the creator of Nanny State , a tiny alternative to React. He can be found on Twitter @daz4126.

SitePoint Premium

Multiple Variable Assignment in JavaScript

  • JavaScript Howtos
  • Multiple Variable Assignment in …

Use the = Operator to Assign Multiple Variable in JavaScript

Multiple variable assignment using destructuring assignment with fill() function in javascript.

Multiple Variable Assignment in JavaScript

This tutorial explains multiple variable assignments in JavaScript because variables are the most important part of our coding.

Sometimes, we have to do many variable declarations and assignments as they have the same value. How? Let’s understand.

Assume we have variable1 , variable2 , and variable3 and want all three variables to have a value of 1 .

They seem equivalent, but they are not. The reason is variables’ scope and assignment precedence .

The assignment operator is right-associative in JavaScript, which means it parses the left-most after parsing the right-most.

Let’s have another example to understand variable scope and assignment precedence .

Focus on the code and see that variable1 , variable2 , and variable3 are in function scope and local to the test1() .

They are not available outside of test1() method that’s why returning undefined . Here, var variable1 = 1, variable2 = 1, varialbe3 = 1; is equivalent to var variable1 = 1; var variable2 = 1; var varialbe3 = 1; .

Now, observe the test2() function. The variable1 is in function scope due to the var keyword, but variable2 and variable3 are leaking because they are not written with the var keyword.

They are globally accessible outside the test2() function. Remember that the variable declarations are hoisted only.

However, the precedence is right-associative which means var variable1 = (window.variable2 =(window.variable3 = 1)); .

Which Means the variable3 will be assigned to 1 first, then the value of variable3 will be allocated to variable2 , and lastly, the value of variable2 will be assigned to variable1 .

To avoid a variable leak in test2() , we can split the variable declaration and assignment into two separate lines. In this way, we can restrict variable1 , variable2 , and variable3 to test2() function scope.

The destructuring assignment helps in assigning multiple variables with the same value without leaking them outside the function.

The fill() method updates all array elements with a static value and returns the modified array. You can read more about fill() here .

Mehvish Ashiq avatar

Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.

Related Article - JavaScript Variable

  • How to Access the Session Variable in JavaScript
  • How to Check Undefined and Null Variable in JavaScript
  • How to Mask Variable Value in JavaScript
  • Why Global Variables Give Undefined Values in JavaScript
  • How to Declare Multiple Variables in a Single Line in JavaScript
  • How to Declare Multiple Variables in JavaScript

Popular Tutorials

Popular examples, reference materials, learn python interactively, javascript object methods.

  • JavaScript assign()
  • JavaScript create()
  • JavaScript defineProperties()
  • JavaScript defineProperty()
  • JavaScript entries()
  • JavaScript freeze()
  • JavaScript fromEntries()
  • JavaScript getOwnPropertyDescriptor()
  • JavaScript getOwnPropertyDescriptors()
  • JavaScript getOwnPropertyNames()
  • JavaScript getOwnPropertySymbols()
  • JavaScript getPrototypeOf()
  • JavaScript hasOwnProperty()
  • JavaScript is()
  • JavaScript isExtensible()
  • JavaScript isFrozen()
  • JavaScript isPrototypeOf()
  • JavaScript isSealed()
  • JavaScript keys()
  • JavaScript preventExtensions()
  • JavaScript propertyIsEnumerable()
  • JavaScript seal()
  • JavaScript setPrototypeOf()
  • JavaScript toLocaleString()
  • JavaScript toString()
  • JavaScript valueOf()
  • JavaScript values()

JavaScript Tutorials

JavaScript Object.keys()

JavaScript Object.values()

JavaScript Object.getOwnPropertyNames()

JavaScript Object.is()

  • Javascript Object.defineProperties()
  • JavaScript Object.entries()

JavaScript Object.assign()

The Object.assign() method copies all the enumerable properties of the given objects to a single object and returns it.

assign() Syntax

The syntax of the assign() method is:

Here, assign() is a static method. Hence, we need to access the method using the class name, Object .

assign() Parameters

The assign() method takes in:

  • target - the target object to which we will copy all the properties of the sources .
  • sources - the source object(s) whose properties we want to copy.

assign() Return Value

The assign() method returns the target object.

Note: Properties in the target object are overwritten by properties in the sources if they have the same key.

Example 1: Javascript Object.assign() to Clone Objects

In the above example, we have used the assign() method to assign the contents of obj to newObject .

Since assign() modifies the target object and returns the same object, both copy and newObject are clones of one another. As a result, we get identical outputs when we print them both.

Example 2: assign() to Merge Objects

In the above example, we have used assign() to merge the objects o1 , o2 , and o3 into a new object o4 .

Using the empty object {} as a target object ensures that the properties of the other objects are copied to a new object without modifying any of the source objects.

As can be seen from the output, properties of later objects overwrite that of earlier ones. For example,

  • the b key from o1 is overwritten by its counterpart in o2 .
  • the c keys from o1 and o2 are overwritten by their counterpart in o3 .

Note: If the source value is a reference to an object, it only copies the reference value.

Sorry about that.

Related Functions

JavaScript Library

livingwithcode logo

  • Python Guide

Declare Multiple Variables in a Single Line in JavaScript

By James L.

The most common way to declare multiple variables in JavaScript is to declare each variable individually on its own line.

For example:

However, there are times when you may want to group related variables together to provide a clear context of their usage. This is where declaring multiple variables on one line can be handy.

In JavaScript, there are several ways to declare multiple variables in a single line.

In this blog post, we will discuss the following methods:

Using comma separator

Using destructuring assignment with arrays and objects.

To declare multiple variables in JavaScript, you can use the var , let or const keyword followed by a comma-separated list of variable names, each initialized with corresponding values

var x = 5, y = 10, z = 15;

let x = 5, y = 10, z = 15;

const x = 5, y = 10, z = 15;

Avoid using var unless you absolutely have to, such as when supporting old browsers. This is because var variables can be redeclared and reassigned anywhere in your code, which can lead to unexpected behavior.

Do keep in mind that variables declared with the const keyword cannot be reassigned later in JavaScript. This means that their value cannot be changed once it has been initialized.

You can also declare multiple variables of different data types in a single line.

If you do not know the value of variables at the time of declaration then you can declare multiple variables using var or let keyword and assign their values later as follows:

However, you cannot use const keyword to declare multiple variables in one line and assign their values later.

This is because each variable created with const keyword must be initialized with a value at the time of declaration.

For example, this is not allowed:

Another way to assign multiple variables in JavaScript is to use the destructuring assignment, which allows you to unpack values from arrays or properties from objects into distinct variables.

Destructuring assignment makes sense when you have an array or object and want to extract its values to variables.

In general, it is best to declare each variable on a separate line, with its own assignment statement. This makes your code more readable and easier to maintain.

However, there are cases where it may be convenient to declare multiple variables on one line, such as when you are grouping related together, or when you are extracting values from an object or array using destructuring assignment.

Use single line multiple variable assignment sparingly.

Destructuring assignment

The two most used data structures in JavaScript are Object and Array .

  • Objects allow us to create a single entity that stores data items by key.
  • Arrays allow us to gather data items into an ordered list.

However, when we pass these to a function, we may not need all of it. The function might only require certain elements or properties.

Destructuring assignment is a special syntax that allows us to “unpack” arrays or objects into a bunch of variables, as sometimes that’s more convenient.

Destructuring also works well with complex functions that have a lot of parameters, default values, and so on. Soon we’ll see that.

Array destructuring

Here’s an example of how an array is destructured into variables:

Now we can work with variables instead of array members.

It looks great when combined with split or other array-returning methods:

As you can see, the syntax is simple. There are several peculiar details though. Let’s see more examples to understand it better.

It’s called “destructuring assignment,” because it “destructurizes” by copying items into variables. However, the array itself is not modified.

It’s just a shorter way to write:

Unwanted elements of the array can also be thrown away via an extra comma:

In the code above, the second element of the array is skipped, the third one is assigned to title , and the rest of the array items are also skipped (as there are no variables for them).

…Actually, we can use it with any iterable, not only arrays:

That works, because internally a destructuring assignment works by iterating over the right value. It’s a kind of syntax sugar for calling for..of over the value to the right of = and assigning the values.

We can use any “assignables” on the left side.

For instance, an object property:

In the previous chapter, we saw the Object.entries(obj) method.

We can use it with destructuring to loop over the keys-and-values of an object:

The similar code for a Map is simpler, as it’s iterable:

There’s a well-known trick for swapping values of two variables using a destructuring assignment:

Here we create a temporary array of two variables and immediately destructure it in swapped order.

We can swap more than two variables this way.

The rest ‘…’

Usually, if the array is longer than the list at the left, the “extra” items are omitted.

For example, here only two items are taken, and the rest is just ignored:

If we’d like also to gather all that follows – we can add one more parameter that gets “the rest” using three dots "..." :

The value of rest is the array of the remaining array elements.

We can use any other variable name in place of rest , just make sure it has three dots before it and goes last in the destructuring assignment.

Default values

If the array is shorter than the list of variables on the left, there will be no errors. Absent values are considered undefined:

If we want a “default” value to replace the missing one, we can provide it using = :

Default values can be more complex expressions or even function calls. They are evaluated only if the value is not provided.

For instance, here we use the prompt function for two defaults:

Please note: the prompt will run only for the missing value ( surname ).

Object destructuring

The destructuring assignment also works with objects.

The basic syntax is:

We should have an existing object on the right side, that we want to split into variables. The left side contains an object-like “pattern” for corresponding properties. In the simplest case, that’s a list of variable names in {...} .

For instance:

Properties options.title , options.width and options.height are assigned to the corresponding variables.

The order does not matter. This works too:

The pattern on the left side may be more complex and specify the mapping between properties and variables.

If we want to assign a property to a variable with another name, for instance, make options.width go into the variable named w , then we can set the variable name using a colon:

The colon shows “what : goes where”. In the example above the property width goes to w , property height goes to h , and title is assigned to the same name.

For potentially missing properties we can set default values using "=" , like this:

Just like with arrays or function parameters, default values can be any expressions or even function calls. They will be evaluated if the value is not provided.

In the code below prompt asks for width , but not for title :

We also can combine both the colon and equality:

If we have a complex object with many properties, we can extract only what we need:

The rest pattern “…”

What if the object has more properties than we have variables? Can we take some and then assign the “rest” somewhere?

We can use the rest pattern, just like we did with arrays. It’s not supported by some older browsers (IE, use Babel to polyfill it), but works in modern ones.

It looks like this:

In the examples above variables were declared right in the assignment: let {…} = {…} . Of course, we could use existing variables too, without let . But there’s a catch.

This won’t work:

The problem is that JavaScript treats {...} in the main code flow (not inside another expression) as a code block. Such code blocks can be used to group statements, like this:

So here JavaScript assumes that we have a code block, that’s why there’s an error. We want destructuring instead.

To show JavaScript that it’s not a code block, we can wrap the expression in parentheses (...) :

Nested destructuring

If an object or an array contains other nested objects and arrays, we can use more complex left-side patterns to extract deeper portions.

In the code below options has another object in the property size and an array in the property items . The pattern on the left side of the assignment has the same structure to extract values from them:

All properties of options object except extra that is absent in the left part, are assigned to corresponding variables:

Finally, we have width , height , item1 , item2 and title from the default value.

Note that there are no variables for size and items , as we take their content instead.

Smart function parameters

There are times when a function has many parameters, most of which are optional. That’s especially true for user interfaces. Imagine a function that creates a menu. It may have a width, a height, a title, items list and so on.

Here’s a bad way to write such a function:

In real-life, the problem is how to remember the order of arguments. Usually IDEs try to help us, especially if the code is well-documented, but still… Another problem is how to call a function when most parameters are ok by default.

That’s ugly. And becomes unreadable when we deal with more parameters.

Destructuring comes to the rescue!

We can pass parameters as an object, and the function immediately destructurizes them into variables:

We can also use more complex destructuring with nested objects and colon mappings:

The full syntax is the same as for a destructuring assignment:

Then, for an object of parameters, there will be a variable varName for property incomingProperty , with defaultValue by default.

Please note that such destructuring assumes that showMenu() does have an argument. If we want all values by default, then we should specify an empty object:

We can fix this by making {} the default value for the whole object of parameters:

In the code above, the whole arguments object is {} by default, so there’s always something to destructurize.

Destructuring assignment allows for instantly mapping an object or array onto many variables.

The full object syntax:

This means that property prop should go into the variable varName and, if no such property exists, then the default value should be used.

Object properties that have no mapping are copied to the rest object.

The full array syntax:

The first item goes to item1 ; the second goes into item2 , all the rest makes the array rest .

It’s possible to extract data from nested arrays/objects, for that the left side must have the same structure as the right one.

We have an object:

Write the destructuring assignment that reads:

  • name property into the variable name .
  • years property into the variable age .
  • isAdmin property into the variable isAdmin (false, if no such property)

Here’s an example of the values after your assignment:

The maximal salary

There is a salaries object:

Create the function topSalary(salaries) that returns the name of the top-paid person.

  • If salaries is empty, it should return null .
  • If there are multiple top-paid persons, return any of them.

P.S. Use Object.entries and destructuring to iterate over key/value pairs.

Open a sandbox with tests.

Open the solution with tests in a sandbox.

  • If you have suggestions what to improve - please submit a GitHub issue or a pull request instead of commenting.
  • If you can't understand something in the article – please elaborate.
  • To insert few words of code, use the <code> tag, for several lines – wrap them in <pre> tag, for more than 10 lines – use a sandbox ( plnkr , jsbin , codepen …)

Lesson navigation

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

Home » JavaScript Tutorial » Returning Multiple Values from a Function

Returning Multiple Values from a Function

Summary : in this tutorial, you will learn to define JavaScript functions that return multiple values.

JavaScript functions can return a single value. To return multiple values from a function, you can pack the return values as elements of an array or as properties of an object .

Returning multiple values from a function using an array

Suppose the following getNames() function retrieves the first name and last name from a database in the backend or from the result of a third-party API call and returns them as elements of an array:

The following shows how to get the return value from the getNames() function:

Because the names variable is an array, you can reference its elements using the square brackets, like this:

In ES6, you can use the destructuring assignment syntax to unpack values from an array more intuitively, like this:

In this code, the firstName and lastName variables will take the first and second elements of the return array.

Returning multiple values from an function using an object

If you want to assign a name to each returned value to make it more readable and easier to maintain, you can use an object :

Since the names of the properties are the same as the variables, you can shorten it using the object literal syntax extensions in ES6 as follows:

And you can get the return value as an object like this:

If you want to unpack properties from an object, you can use the object destructuring syntax as follows:

  • JavaScript doesn’t support functions that return multiple values. However, you can wrap multiple values into an array or an object and return the array or the object.
  • Use destructuring assignment syntax to unpack values from the array, or properties from objects.

IMAGES

  1. [Solved] Multiple assignment in javascript? What does

    javascript multiple assignment from object

  2. How To Pass Multiple Variables Into A Javascript Function

    javascript multiple assignment from object

  3. Javascript Assignment Operators (with Examples)

    javascript multiple assignment from object

  4. JavaScript Multiple Inputs Code Along + Challenge

    javascript multiple assignment from object

  5. JS: Assigning values to multiple variables : r/learnjavascript

    javascript multiple assignment from object

  6. 36 Add Property To Object Javascript Es6

    javascript multiple assignment from object

VIDEO

  1. Remove Properties From JavaScript Object (Copy) #javascript #javascriptlearning #javascriptdeveloper

  2. JavaScript Part-31

  3. Session 3 JavaScript Object Literal and Prototype part2 practical

  4. JavaScript Object

  5. How to use Destructuring Assignment in JavaScript

  6. Ch06 JavaScript Qs 01-08

COMMENTS

  1. How to assign multiple variables at once in JavaScript?

    If you aren't absolutely married to the idea of the values being at the end of the statement, this works: var a = "one", b = "two"; If you want to assign to variables that have already been declared, you can use the comma operator to make it a one-liner. a = "ONE", b = "TWO"; answered May 13, 2022 at 13:36. Ryan.

  2. How to assign multiple values to a JavaScript object?

    Say that I have an object with key/value pair as the following: var someVar = { color: "white", font_size: "30px", font_weight: "normal" ...some more variables and functions }; Is there a way to do a multiple assignment to those keys instead of having to do something like this: someVar.color = "blue"; someVar.font_size = "30px"; ...

  3. Object.assign()

    Later sources' properties overwrite earlier ones. The Object.assign() method only copies enumerable and own properties from a source object to a target object. It uses [[Get]] on the source and [[Set]] on the target, so it will invoke getters and setters. Therefore it assigns properties, versus copying or defining new properties.

  4. Destructuring assignment

    The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. Try it. Syntax. js. ... As for object assignment, the destructuring syntax allows for the new variable to have the same name or a different name than the original property, and ...

  5. Object.assign() in JavaScript

    The `Object.assign()` function lets you assign properties from one object to another. You can use it to shallow copy objects or assign multiple properties at once.

  6. Understanding Object.assign() Method in JavaScript

    The Object.assign() method was introduced in ES6 that copies all enumerable own properties from one or more source objects to a target object, and returns the target object. The Object.assign() method invokes the getters on the source objects and setters on the target object. It assigns properties only, not copying or defining new properties.

  7. Using JavaScript Object.assign() Method in ES6

    The following shows the syntax of the Object.assign() method: Object.assign ( target, .. .sources) Code language: CSS (css) The Object.assign() copies all enumerable and own properties from the source objects to the target object. It returns the target object. The Object.assign() invokes the getters on the source objects and setters on the target.

  8. Working with objects

    A method is a function associated with an object, or, put differently, a method is a property of an object that is a function. Methods are defined the way normal functions are defined, except that they have to be assigned as the property of an object. See also method definitions for more details. An example is:

  9. Object.assign()

    Description. Properties in the target object will be overwritten by properties in the sources if they have the same key. Later sources' properties will similarly overwrite earlier ones. The Object.assign() method only copies enumerable and own properties from a source object to a target object. It uses [[Get]] on the source and [[Set]] on the ...

  10. Understanding Object.assign () in JavaScript

    Object.assign() is a powerful method in JavaScript that allows developers to clone objects, merge multiple objects, handle nested objects, and combine multiple sources into a single object. Understanding and utilizing Object.assign() correctly can greatly improve efficiency and readability in JavaScript code.

  11. A Guide to Variable Assignment and Mutation in JavaScript

    In JavaScript, variable assignment refers to the process of assigning a value to a variable. For example, let x = 5; Here, we are assigning the value 5 to the variable x. On the other hand ...

  12. Multiple Variable Assignment in JavaScript

    Output: 1, 1, 1, 1. undefined. The destructuring assignment helps in assigning multiple variables with the same value without leaking them outside the function. The fill() method updates all array elements with a static value and returns the modified array. You can read more about fill() here.

  13. JavaScript Object.assign()

    In the above example, we have used assign() to merge the objects o1, o2, and o3 into a new object o4. const o4 = Object.assign({}, o1, o2, o3); Using the empty object {} as a target object ensures that the properties of the other objects are copied to a new object without modifying any of the source objects.

  14. Declare Multiple Variables in a Single Line in JavaScript

    To declare multiple variables in JavaScript, you can use the var, let or const keyword followed by a comma-separated list of variable names, each initialized with corresponding values. For example: var x = 5, y = 10, z = 15; Or. let x = 5, y = 10, z = 15; Or. const x = 5, y = 10, z = 15; Avoid using var unless you absolutely have to, such as ...

  15. Assignment (=)

    The assignment operator is completely different from the equals (=) sign used as syntactic separators in other locations, which include:Initializers of var, let, and const declarations; Default values of destructuring; Default parameters; Initializers of class fields; All these places accept an assignment expression on the right-hand side of the =, so if you have multiple equals signs chained ...

  16. How to Merge Objects in JavaScript

    When we merged these objects, the result object (remoteJob) has the country property with the value from the second object (location). Merge objects using Object.assign() method. The Object.assign() method allows you to copy all enumerable own properties from one or more source objects to a target object, and return the target object:

  17. Destructuring assignment

    If an object or an array contains other nested objects and arrays, we can use more complex left-side patterns to extract deeper portions. In the code below options has another object in the property size and an array in the property items. The pattern on the left side of the assignment has the same structure to extract values from them:

  18. Returning Multiple Values from a Function

    Returning multiple values from an function using an object. If you want to assign a name to each returned value to make it more readable and easier to maintain, you can use an object: function getNames() {. // get names from the database or API let firstName = 'John' , lastName = 'Doe' ; // return values return {.

  19. Assign multiple variables to the same value in Javascript?

    The original variables you listed can be declared and assigned to the same value in a short line of code using destructuring assignment. The keywords let, const, and var can all be used for this type of assignment. let [moveUp, moveDown, moveLeft, moveRight, mouseDown, touchDown] = Array(6).fill(false); answered Jul 20, 2020 at 2:17.

  20. JavaScript

    var allUsers = []; // Populate users array. for(var key in users) {. allUsers.push(users[key]); } One last note on style. You should probably avoid explicitly setting the 'key' of each user object in your users object literal to be the name of the user. If you have any users with the same name, this model will break.

  21. Array

    The Array object, as with arrays in other programming languages, enables storing a collection of multiple items under a single variable name, and has members for performing common array operations. ... (All standard built-in copy operations with any JavaScript objects create shallow copies, rather than deep copies). Array indices.