gaearon / ama

Ask me anything!
222 stars 5 forks source link

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

Open cezarneaga opened 8 years ago

cezarneaga commented 8 years ago

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

Youmoo commented 8 years ago

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.

cezarneaga commented 8 years ago

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 :)

srobinson commented 8 years ago

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