DEV Community

Cover image for JavaScript Object Magic
Clever Cottonmouth
Clever Cottonmouth

Posted on

JavaScript Object Magic

const person = {
  firstName: 'ajay',
  lastName: 'kumar',
  hobbies: ['cricket', 'football']
};

let employee = person;
employee.hobbies.push('hockey');

console.log(person);
console.log(employee);

Enter fullscreen mode Exit fullscreen mode

Explanation:
The person object is created with properties firstName, lastName, and hobbies (an array).
The variable employee is assigned the reference of person, meaning both person and employee point to the same object in memory.
When you modify employee.hobbies by adding 'hockey', it affects the original person object because both person and employee are pointing to the same object.
As a result, printing both person and employee will output the same modified object.

{
  firstName: 'ajay',
  lastName: 'kumar',
  hobbies: ['cricket', 'football', 'hockey']
}
{
  firstName: 'ajay',
  lastName: 'kumar',
  hobbies: ['cricket', 'football', 'hockey']
}

Enter fullscreen mode Exit fullscreen mode

How to Avoid This (If Needed):
If you want employee to be a separate copy of person (without affecting person when modified), you need to deep clone the object:

Using structuredClone() (Best for deep copying)

let employee = structuredClone(person);
employee.hobbies.push('hockey');
console.log(person);
console.log(employee);

Enter fullscreen mode Exit fullscreen mode

Using JSON.parse(JSON.stringify(person)) (Alternative)

let employee = JSON.parse(JSON.stringify(person));
employee.hobbies.push('hockey');
console.log(person);
console.log(employee);

Enter fullscreen mode Exit fullscreen mode

Top comments (0)