0

I came across this pattern for JavaScript initialization:

foo = foo || {};
alert('no errors!');

But it seems that it does not work unless foo was defined before.

There are two variations of the same pattern that seem to work correctly:

var foo = foo || {};
alert('no errors!');

and

foo = window.foo || {};
alert('no errors!');

From my point of view, I don't understand why the first one does not work, but the two other do.

Why is that? Could you please explain in detail?

1

2 Answers 2

2

Javascript has a global object. In the browser, this is referenced by the name window.

window.foo create a property in the global object.

var foo create a global variable. This is very similar to a property of the global object, but you can't use delete on it.

Simply declaring foo without the var keyword also create a property on the global object. It is a language design choice -- a lousy one -- but a design choice none-the-less.

var foo and window.foo both work equally well when you are at the global level. If you are inside of a function -- perhaps a module -- you must use window.foo to make sure you reach the global object.

Sign up to request clarification or add additional context in comments.

4 Comments

So you are saying that even when I use window.foo on the right-hand side of the assignment, it still creates the window.foo variable with the value of undefined?
No, it creates a property on the window object. To create a variable you use var. However -- when you access a property of any object that doesn't exist, you get the value of undefined. So ... window.XYZZYFOOBAR will be undefined because it doesn't exist.
OK, I understand it now. The problem was undeclared foo. The reason why first alternative was working was because it declared it, the reason why second alternative was working because accessing non-existing property does not cause an ReferenceError as it does on non-declared variable. Thank you.
Bingo! You've got it.
1

You can't read a variable which isn't defined (that's a reference error). That's why

something = foo;

will lead to an error if the foo variable isn't declared. window is declared of course and there's no problem querying its property foo.

2 Comments

You can read a variable that is not defined, you can't read one that is not declared.
@Quentin You mean a variable whose value isn't defined. But I change the wording to be less ambiguous.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.