Introduction
In this lab, we will explore the concept of shallow cloning in JavaScript. Shallow cloning creates a new object with all of the properties of the original object, but the properties themselves are not cloned. Instead, they are copied by reference, which means that any changes made to the properties of the original object will also be reflected in the cloned object. Through this lab, we will understand how to create shallow clones of objects using the Object.assign() method in JavaScript.
How to Create a Shallow Clone of an Object
To create a shallow clone of an object, use Object.assign() and an empty object ({}). Follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use the following code to create a shallow clone of the original object:
const shallowClone = (obj) => Object.assign({}, obj);
- To clone the object, use the
shallowClone()function as follows:
const a = { x: true, y: 1 };
const b = shallowClone(a); // a !== b
In this example, a and b are two different objects, but they have the same values.
Summary
Congratulations! You have completed the Shallow Clone Object lab. You can practice more labs in LabEx to improve your skills.