Understanding Object Assignment in JavaScript
Let's explore how object assignment works in JavaScript using the following example:
let c = { greeting: 'Hey!' };
let d;
d = c;
c.greeting = 'Hello';
console.log(d.greeting);
What do you think the output of console.log(d.greeting)
would be?
The output would be:
Hello
Let's understand why:
1. let c = { greeting: 'Hey!' };
: This line declares a variable c
and assigns it an object with a greeting
property set to 'Hey!'
.
2. let d;
: This line declares a variable d
but doesn't assign it any value yet.
3. d = c;
: Here, d
is assigned the same object that c
is referencing. Both c
and d
now point to the same object in memory.
4. c.greeting = 'Hello';
: This line modifies the greeting
property of the object referenced by c
to 'Hello'
.
5. console.log(d.greeting);
: Since d
points to the same object as c
, accessing the greeting
property of d
also reflects the change made to the object through c
. Thus, the output is 'Hello'
.
This demonstrates how object assignment works in JavaScript, where variables pointing to objects reference the same underlying object in memory.