Luke Schlangen
Luke Schlangen

Reputation: 3882

Why is length equal to 0 in browser before it is defined?

I would expect the value of an undefined variable in javascript to behave like this when it is logged:

enter image description here

But on jsfiddle it is showing the length is 0 before it is ever defined.

enter image description here

After more research. It also seems to default to 0 in chrome.

enter image description here

When I would expect it to generate an error like with any other randomWord

enter image description here

When I run the same commands in node locally, it seems to behave how I would expect. With throwing an error for length:

enter image description here

Why is length equal to 0 in these cases?

Upvotes: 0

Views: 104

Answers (3)

Yichong
Yichong

Reputation: 727

Try this: console.log("length" in window), then you will know if it is defined in the global object.

Upvotes: 0

CodingYoshi
CodingYoshi

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

Felix Kling
Felix Kling

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

Related Questions