Computer >> Computer tutorials >  >> Programming >> Javascript

Shortest syntax to assign properties from function call to an existing object in JavaScript


For this, use the following −

{... anyObjectName1,...anyObjectName2}.

Example

Following is the code −

function getTheObject() {
   return {
      lastName: "Smith",
      countryName:"US"
   }
}
var availableObj = { firstName: "Adam" }
availableObj = { ...availableObj, ...getTheObject() };
console.log(availableObj);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo313.js.

Output

This will produce the following output −

PS C:\Users\Amit\javascript-code> node demo313.js
{ firstName: 'Adam', lastName: 'Smith', countryName: 'US' }