I have the following bit of code:
(function(){
...
var n = n || {};
...
})();
This does what I want, setting n equal to {} since this is the first time it’s encountered and will be undefined. Unfortunately, since this inside a function, n is limited in scope to the function and I can’t use it in other scripts.
I wanted to just change the line to n = n || {}, but I got an error: ReferenceError: n is not defined
Changing it to just n = {} worked as expected; however, this is not what I want. I don’t get why n‘s undefinedness causes an error when I don’t use var and works as expected (being a falsey value used to get the right side of the OR statement) when I do. Based on my understanding of the var keyword, I would expect it to be both or neither.
Why does the var matter, what is going on here?
So it sounds like you’re having trouble creating a global variable.
Good.
Creating global variables in JavaScript is easier than it should be.
Your problem is that
nis not defined (duh). You can’t reference a variable that’s not yet defined. But you’re probably thinking, “How is that different from the version usingvar???” And that’s a good question.JavaScript does something called “hoisting” of variable definitions. If you define a variable within a function, that definition gets implicitly relocated to the top of the function. So while you wrote:
What really happened was closer to:
However, it’s not really that simple, because if you tried to write that code, you’d wind up with
nalways being set to{}. But the general essence is there. The variable declaration happens before the assignment.If you remove the
var, it will cause a reference error because there’s no declaration to hoist anymore. So one “proper” (and I use that term loosely, because it’s never “proper” to create a global variable) way to do what you want is to take yourvarand place it outside your function wrapper. Like so:Unfortunately, you can’t do it like this:
That has the same “problem” as my example above. If
nis defined elsewhere, it will be set toundefinedby thevar n;and then set to{}in the function. By doing the whole declaration and assignment outside the function, you get what you’re looking for. Which I assume (based on the title of your question) is actually namespacing and not some arbitrary global variable. That would be naughty! 😉UPDATE:
Oh, and by the way, a better way to do this might be by explicitly referencing the global object:
This will probably play better with things like node.js and anything that might wrap your code (like a
$(function() { })).