Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Shortest syntax to assign properties from function call to an existing object in JavaScript
In JavaScript, you can quickly assign properties from a function call to an existing object using several concise syntaxes. This article explores the most efficient approaches to merge function-returned properties into existing objects.
An object in JavaScript is a separate entity having properties and a type. JavaScript objects can have properties that specify their attributes.
Using Spread Syntax (...)
The spread syntax provides the shortest way to assign properties from a function call to an existing object. It expands an object's properties into a new object, effectively merging them.
Syntax
existingObject = { ...existingObject, ...functionCall() };
Example
In the following example, we use spread syntax to merge properties from a function call into an existing object:
<!DOCTYPE html>
<html>
<body>
<p id="tutorial"></p>
<script>
function getCarData() {
return {
car1: "BMW",
car2: "TESLA"
};
}
let existingObject = { car3: "BENZ" };
existingObject = { ...existingObject, ...getCarData() };
document.getElementById("tutorial").innerHTML = JSON.stringify(existingObject);
</script>
</body>
</html>
{"car3":"BENZ","car1":"BMW","car2":"TESLA"}
Using Object.assign()
The Object.assign() method copies enumerable properties from source objects to a target object. It modifies the original object directly, unlike spread syntax which creates a new object.
Syntax
Object.assign(targetObject, functionCall());
Example
Here's how to use Object.assign() to merge function-returned properties:
<!DOCTYPE html>
<html>
<body>
<p id="tutorial"></p>
<script>
function getVehicleData() {
return {
num: 22,
vehicle: "bike"
};
}
let someObject = {
num: 25,
coffee: "black"
};
Object.assign(someObject, getVehicleData());
document.getElementById("tutorial").innerHTML = JSON.stringify(someObject);
</script>
</body>
</html>
{"num":22,"coffee":"black","vehicle":"bike"}
Comparison
| Method | Creates New Object? | Modifies Original? | Syntax Length |
|---|---|---|---|
| Spread Syntax | Yes | No | Shorter |
| Object.assign() | No | Yes | Slightly longer |
Key Points
- Spread syntax is generally preferred for its immutability and concise syntax
- Object.assign() is useful when you want to modify the original object
- Both methods handle property conflicts by letting the source object's properties override the target's
- Function calls are evaluated once during the assignment process
Conclusion
The spread syntax { ...existingObject, ...functionCall() } provides the shortest and most readable way to assign properties from function calls to existing objects. Use Object.assign() when you need to modify the original object directly.
