nicael
nicael

Reputation: 18995

Why this alert returns undefined

alert(0==false);   //true; as expected
alert("a"[0]);     //a; as expected
alert("a"[false]); //undefined; why?

So why?

Upvotes: 0

Views: 78

Answers (2)

adeneo
adeneo

Reputation: 318252

The string "a" only has a 0 index, the first and only character.

0 == false is true, as 0 is falsy, but 0 === false is false as they are not the same type, and passing false as the index doesn't make it the number 0 even if they both evaluate to falsy, which is why it's undefined

Upvotes: 3

Felix Kling
Felix Kling

Reputation: 816600

Whenever you a trying to access a property via bracket notation, the value of the expression is converted to a string. Thus, "a"[false], really is "a"['false'], and "a"[0] is actually "a"['0']. Both property names are obviously very different..

In 0==false, false is converted to a number which is indeed 0.


In other words: Number(false) and String(false) produce two different values, and thus, even though 0 == false, "a"[0] !== "a"[false].

Upvotes: 6

Related Questions