Reputation: 2699
Why does accessing false.bar
not throw an error while undefined.bar
does?
var foo1 = false;
var foo2;
console.log(foo1.bar); // undefined
console.log(foo2.bar); // Uncaught TypeError: Cannot read property 'bar' of undefined
Upvotes: 0
Views: 344
Reputation: 6561
Look around for "boxing", you'll find that many answers have already been written.
To sum it up, Boolean
, Number
and String
instances will magically "box" primitive values in a context where you're treating them as objects. Booleans don't have any useful methods or properties except the default Object-inherited ones, so you'll never see boolean boxing. But the language allows it.
However, there are no Null
or Undefined
constructors to box those values, so trying to access properties of null
and undefined
is an error.
Upvotes: 1
Reputation: 1569
It's because false
itself is an object, while undefined
isn't.
Variable is undefined
if it wasn't assigned a value yet, like foo2
in your code. You're trying to access a property of something that doesn't exist, so JS gets scared and throws error.
When you're trying to access foo1
, the object foo1
exists, since you've assigned false
to it. JS doesn't mind that this object doesn't have a "bar" property and will just return undefined
, as in "this property isn't defined yet".
Upvotes: 0
Reputation: 167
In your example, foo1 actually exists, so we can check for a property on it (it has no property defined called "bar", so we get a undefined for that).
The other case, foo2, doesnt exists (it never has been init and is still undefined), so trying to check for a property will result in a error.
Upvotes: 0