Shallow Clone Object

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/destr_assign("`Destructuring Assignment`") subgraph Lab Skills javascript/variables -.-> lab-28613{{"`Shallow Clone Object`"}} javascript/data_types -.-> lab-28613{{"`Shallow Clone Object`"}} javascript/arith_ops -.-> lab-28613{{"`Shallow Clone Object`"}} javascript/comp_ops -.-> lab-28613{{"`Shallow Clone Object`"}} javascript/destr_assign -.-> lab-28613{{"`Shallow Clone Object`"}} end

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:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use the following code to create a shallow clone of the original object:
const shallowClone = (obj) => Object.assign({}, obj);
  1. 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.

Other JavaScript Tutorials you may like