ama icon indicating copy to clipboard operation
ama copied to clipboard

new String("a") == new String("a") is false???

Open cezarneaga opened this issue 8 years ago • 3 comments

hi Dan,

love how you explain weird things simply. could you give this a try?

why is new String("a") == new String("a") false? same with all primitives... ref: http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3 NOTE 3 for example.

thanks! Cezar

cezarneaga avatar Jul 06 '16 14:07 cezarneaga

My understanding:

  1. new always returns a newly created object, and thus typeof new String('a') === 'object'. reference
  2. x==y returns true if x and y refer to the same object. Otherwise, return false.Reference:1.f.

In your example new String("a") == new String("a"), new called twice, so two distinct objects are created , so false returned.

Sorry for my not-so-good English.

Youmoo avatar Jul 07 '16 06:07 Youmoo

thanks @Youmoo ! your english is excellent. don't apologise. no need. :)

that's what i need the explanation for. the distinct objects are the same except the reference the compiler gives it? where does the reference lie in? in global scope? how does the engine know its different. where is the compiler looking to tell its a different one? is the compiler checking the reference only? is there a way to look the reference up?

why doesnt it coerce ?

i guess its more of a philosophical question :)

cezarneaga avatar Jul 07 '16 12:07 cezarneaga

Hi @cezarneaga - in chrome V8 this is achieved using hidden classes and inline caches. This is an excellent talk:

https://www.youtube.com/watch?v=FrufJFBSoQY

srobinson avatar Jul 10 '16 10:07 srobinson