And then comes another question -
Q. After the following JavaScript code is run which of the following statements will evaluate to true?
var Person = function(firstName, lastName, dateOfBirth, measurements){
this.firstName = firstName;
this.lastName = lastName;
this.dateOfBirth = dateOfBirth;
this.measurements = measurements;
};
person = new Person("Wonder", "Woman", new Date(2021, 5, 31), {weight: "58kg"})
personClone = JSON.parse(JSON.stringify(person))
// A. person.firstName === personClone.firstName
// B. person.measurements['weight'] === personClone.measurements['weight']
// C. person === personClone
// D. person.dateOfBirth.toDateString() === personClone.dateOfBirth.toDateString()
Choices -
- C
- B D
- A C D
- B C D
- B
- D
- A B C
- A B
- A D
- A C
- B C
- A
Submitted Choice - (2)
Defence - [A, B, D] was not an option so [B, D]. But still, a wrong one.
Quirk/fact - let's take the equations/statements one by one
-
A
: that's going to be a true; since, both of the objects will have the same string value in the property offirstName
. -
B
: that's going to be a true too; since, that's just value stored inmeasurements.weights
, which is same too. -
C
: that's false; sinceJSON.parse
makes a new object from the string passed in to it. So, two different references will cause "tripple equality" to fail. -
D
: that's tricky and missed. LikeB
- it should be the same value but, no. While theperson
is instantiated - thedateOfBirth
is passed in an instance ofDate
, which has the method.toDateString()
. And when theperson
is "stringified", thedateOfBirth
is transformed into a string. While parsing, the stringified form back intopersonClone
- thedateOfBirth
will be astring
rather than aDate
instance. So, no.toDateString()
available topersonClone.dateOfBirth
. -
D
(bonus) - Further, had the statement been -person.dateOfBirth.toDateString() === personClone.dateOfBirth
- still a false. The reason, try answering in comments, if possible and if you're still reading - will add it later though ;)
P.S.: Here is the earlier part, if interested.
:: UPDATE ::
The reason for D
(bonus) is false - the difference in the string lies in the fact that The instances of Date implement the toJSON() function by returning a string (the same as date.toISOString()). Thus, they are treated as strings. - therefore personClone.dateOfBirth
gives the .toISOString()
version but personClone.dateOfBirth.toDateString()
gives just human readable date
...contd. in next part.
Top comments (0)