DEV Community


Posted on • Updated on

f**ing quirk(s) in JS that show(s) up mostly in the interviews - II

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()
Enter fullscreen mode Exit fullscreen mode

Choices -

  1. C
  2. B D
  3. A C D
  4. B C D
  5. B
  6. D
  7. A B C
  8. A B
  9. A D
  10. A C
  11. B C
  12. 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 of firstName.
  • B: that's going to be a true too; since, that's just value stored in measurements.weights, which is same too.
  • C: that's false; since JSON.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. Like B - it should be the same value but, no. While the person is instantiated - the dateOfBirth is passed in an instance of Date, which has the method .toDateString(). And when the person is "stringified", the dateOfBirth is transformed into a string. While parsing, the stringified form back into personClone - the dateOfBirth will be a string rather than a Date instance. So, no .toDateString() available to personClone.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)