Reputation: 3882
I would expect the value of an undefined variable in javascript to behave like this when it is logged:
But on jsfiddle it is showing the length
is 0 before it is ever defined.
After more research. It also seems to default to 0 in chrome.
When I would expect it to generate an error like with any other randomWord
When I run the same commands in node locally, it seems to behave how I would expect. With throwing an error for length:
Why is length equal to 0
in these cases?
Upvotes: 0
Views: 104
Reputation: 727
Try this: console.log("length" in window)
, then you will know if it is defined in the global object.
Upvotes: 0
Reputation: 27009
If you do not qualify length
property then JS will go up the hierarchy and see if someone up the hierarchy has the property length
and it happens to be that window
has that property. Therefore, it is not undefined. It is defined.
It is the same as window.length
.
Upvotes: 1
Reputation: 816452
length
is a predefined global variable in browsers:
Returns the number of frames (either
<frame>
or<iframe>
elements) in the window
Upvotes: 3