You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+29Lines changed: 29 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -59,3 +59,32 @@ So the object `a` looks like -
59
59
```
60
60
61
61
</details>
62
+
63
+
<details>
64
+
<summary>
65
+
<h3>2. Guess the output of this code?
66
+
67
+
```js
68
+
let obj1 = { key:"value" };
69
+
let obj2 = obj1;
70
+
let obj3 = obj2;
71
+
72
+
obj1.key="new value";
73
+
obj2 = { key:"another value" };
74
+
75
+
console.log(obj1.key, obj2.key, obj3.key);
76
+
```
77
+
78
+
</h3>
79
+
</summary>
80
+
The output of this code will be `new value``another value``new value`.
81
+
82
+
In this code, we are declaring three variables obj1, obj2, and obj3, and assigning an object to each of them. Then, we are reassigning a new object to obj2 and modifying a property of obj1.
83
+
84
+
When the console.log statement is executed, it logs the values of the key property for each object. The value of the key property for obj1 is "new value", the value of the key property for obj2 is "another value", and the value of the key property for obj3 is "new value".
85
+
86
+
This is because when an object is assigned to a variable, the variable stores a reference to the object in memory rather than the object itself. Changing the value of a property of the object using one variable will affect the value of that property when accessed using a different variable that references the same object. However, reassigning a new object to a variable will change the reference stored in that variable, so the original object is no longer accessible using that variable.
87
+
88
+
In this case, the value of the key property for obj1 was changed to "new value" using the obj1 variable, which affected the value of the key property when accessed using the obj3 variable, because both variables reference the same object. However, the value of the key property for obj2 was not affected, because the obj2 variable was reassigned to reference a new object.
0 commit comments