Three different techniques come to mind, each with its warnings and (except the second one) uses:
1) You can declare a new variable in JavaScript anywhere in the code using the var
keyword:
var $color = 'red';
The variable is actually defined throughout the scope in which the var
occurs, even above the var
statement — that is, these two functions are identical even though they look slightly different:
function foo() {
doSomething();
var x = 5;
x += doSomethingElse();
return x;
}
function foo() {
var x;
doSomething();
x = 5;
x += doSomethingElse();
return x;
}
This is because all var
s take effect when the context for the function is created, not where they appear in the code. More: Poor, misunderstood var
2) If you just assign to a free symbol that's never been declared anywhere, you'll create an implicit global variable (not one constrained to the current scope), which is generally a bad idea. More: The Horror of Implicit Globals
3) Another thing you can do is have an object which is a container for various variables you want to track. You can create new properties on the object just by assigning them:
var data = {}; // A blank object
data.foo = "bar"; // Now `data` has a `foo` property
This technique is particularly handy when you need to track data that your script is completely unaware of, for instance based on user input, because you can use either dotted notation and a literal as above (data.foo
), or you can use bracketed notation and a string (data["foo"]
). In the latter case, the string can be the result of any expression, so all of these create a foo
property on data
:
// Dotted notation with a literal
data.foo = 42;
// Bracketed notation with a literal string
data["foo"] = 42;
// Bracketed notation with a string coming from a variable
s = "foo";
data[s] = 42;
// Bracketed notation with a string coming from an expression
s = "o";
data["f" + s + s] = 42;