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)

Playwright CLI Flags Tutorial

5 Playwright CLI Flags That Will Transform Your Testing Workflow

  • 0:56 --last-failed: Zero in on just the tests that failed in your previous run
  • 2:34 --only-changed: Test only the spec files you've modified in git
  • 4:27 --repeat-each: Run tests multiple times to catch flaky behavior before it reaches production
  • 5:15 --forbid-only: Prevent accidental test.only commits from breaking your CI pipeline
  • 5:51 --ui --headed --workers 1: Debug visually with browser windows and sequential test execution

Learn how these powerful command-line options can save you time, strengthen your test suite, and streamline your Playwright testing experience. Click on any timestamp above to jump directly to that section in the tutorial!

Watch Full Video 📹ī¸

👋 Kindness is contagious

Please leave a ❤ī¸ or a friendly comment on this post if you found it helpful!

Okay