loading
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
Example 1
*/

// Simple object
const simpleObject = {
  firstName: 'param',
  lastname: 'Harrison',
  isMarried: true,
};
// Cloned simple object
const clonedSimpleObject = { ...simpleObject };

simpleObject.firstName = "ABC";
clonedSimpleObject.firstName = "XYZ";

console.log(simpleObject.firstName === clonedSimpleObject.firstName); // False


/*
Example 2
*/

const nestedObject = {
  firstName: 'Param',
  like: ['coffee', 'tea', 'javascript'],
};

const clonedNestedObject = {...nestedObject };

nestedObject.like.push('sleeping');
clonedNestedObject.like.push('swimming');
clonedNestedObject.firstName = "Vennila";

console.log("nestedObject.like === clonedNestedObject.like -> ", nestedObject.like === clonedNestedObject.like); // True
console.log(nestedObject.like, clonedNestedObject.like); // Both are same array - ["coffee", "tea", "javascript", "sleeping", "swimming"]
console.log("nestedObject.firstName === clonedNestedObject.firstName -> ", nestedObject.firstName === clonedNestedObject.firstName); // False


/* 
Example 3
*/

const deepClonedObject = {
  ...nestedObject,
  like: [...nestedObject.like],
};

deepClonedObject.like.push('reading');
console.log("nestedObject.like === deepClonedObject.like -> ", nestedObject.like === deepClonedObject.like); // False
console.log(nestedObject.like, deepClonedObject.like);