At Universal Containers, every team has its own way of copying JavaScript objects. The code snippet shows an implementation from one team:
01 function Person() {
02 this.firstName = "John";
03 this.lastName = "Doe";
04 this.name = () => {
05 console.log('Hello ${this.firstName} ${this.lastName}');
06 }
07 }
08
09 const john = new Person();
10 const dan = JSON.parse(JSON.stringify(john)); // (intended deep copy)
11 dan.firstName = 'Dan';
12 dan.name();
(Original line 10 is logically intended to be JSON.parse(JSON.stringify(john)) to perform a JSON clone.) What is the output of the code execution?
Correct Answer: C
JSON.stringify(john) converts the john object into a JSON string.
When you JSON.parse that string back, you get a plain object:
Only data that can be represented in JSON is preserved (numbers, strings, booleans, arrays, plain objects).
Functions are not preserved and are dropped.
So dan is a plain object with properties firstName and lastName, but no name method.
Therefore, dan.name is undefined, and dan.name() throws:
TypeError: dan.name is not a function
The literal string interpolation inside console.log('Hello ${...}') is also wrong (single quotes), but the code never reaches that line.
________________________________________