A shallow copy in JavaScript copies the top-level structure of an object or array, but for nested objects and arrays, it copies their references instead of creating new copies. This means that changes made to nested objects or arrays in the original object will also be reflected in the shallow copy, and vice versa.
Spread syntax and shallow copy
The spread syntax only creates a new object one level deep.
Example #1
The spread syntax creates a shallow copy of the object property ({ array: [10, 20, 30] }
).
const source = {
prop: "Property",
object: { array: [10, 20, 30] },
};
const copy = { ...source };
copy.object.array[0] = 100;
console.log(source);
If you modify the array
property of the object
property in the copy
variable, it will also affect the source
object. This example demonstrated that the spread syntax creates a shallow copy.
Example #2
The spread syntax creates a shallow copy of the object property ([10, 20, 30]
).
const source = {
prop: "Property",
object: [10, 20, 30],
};
const copy = { ...source };
copy.object[0] = 100;
console.log(source);
If you modify the object
property in the copy
variable, it will also affect the source
object. This example demonstrated that the spread syntax creates a shallow copy.
Object.assign() and shallow copy
Object.assign()
copies all enumerable and own properties from one or more source objects to the target object.
Syntax
const copy = Object.assign(target, source);
const copy = Object.assign(target, source1, source2, ..., sourceN);
Example
const source = {
prop: "Property",
object: { array: [10, 20, 30] },
};
const copy = Object.assign({}, source);
copy.object.array[0] = 100;
console.log(source);
In this example, an empty object {}
is used as the target and source
is the source
object whose properties are copied to the target object copy
. Object.assign({}, source)
created a shallow copy of the source object. This means that it duplicates the top-level properties of the source object into a new object, but it does not deeply clone nested object { array: [10, 20, 30] }
. Instead, it copies their references.