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

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video