Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to copy an object

Short answer

The ... operator creates a new object with the same properties:

const user = { name: 'Anna', age: 25 };
const copy = { ...user };
copy.age = 26;
 
console.log(user.age, copy.age);

Output:

25 26

Nested objects

Such a copy is shallow: nested objects stay shared.

const user = { name: 'Anna', address: { city: 'London' } };
const copy = { ...user };
copy.address.city = 'Paris';
 
console.log(user.address.city);

Output:

Paris

A deep copy

structuredClone() copies the whole object, including all nested data:

const user = { name: 'Anna', address: { city: 'London' } };
const copy = structuredClone(user);
copy.address.city = 'Paris';
 
console.log(user.address.city);

Output:

London

Common mistake

Assigning an object to another variable does not copy it: both variables point to the same object:

const user = { name: 'Anna' };
const copy = user;
copy.name = 'Oleg';
 
console.log(user.name);

Output:

Oleg

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.