In a mechanical sense, you use variables to store, retrieve, and manipulate all the different values that appear in your scripts. Always create a meaningful variable name; that makes it easy for humans to understand what your scripts do.
The first time a variable appears in your script is its declaration. This first mention of the variable sets it up in memory so you can refer to it later on in your script. Always declare variables before using them. You do this using the var keyword.
// A single declaration. var count; // Multiple declarations with a single var keyword. var count, amount, level; // Variable declaration and initialization in one statement. var count = 0, amount = 100;
provide labels for loops.
The first character must be an ASCII letter (either uppercase or lowercase), or an underscore (_) character. Note that a number cannot be used as the first character.
Subsequent characters must be letters, numbers, or underscores.
The variable name must not be a reserved word.
Here are some examples of valid variable names:
_pagecount Part9 Number_Items
Here are some examples of invalid variable names:
// Cannot begin with a number. 99Balloons // The ampersand (&) character is not a valid character for variable names. Alpha&Beta
var currentCount; // finalCount has the value NaN because currentCount is undefined. var finalCount = 1 * currentCount;
You can declare a variable without using the var keyword in the declaration, and assign a value to it. This is an implicit declaration.
You cannot use a variable that has never been declared.
Add a number and a string
The number is coerced into a string.
Add a Boolean and a string
The Boolean is coerced into a string.
Add a number and a Boolean
The Boolean is coerced into a number.
Consider the following example.
// A number. var x = 2000; // A string. var y = "Hello"; // The number is coerced into a string. x = x + y; // Outputs 2000Hello. document.write(x);
Strings are automatically converted to equivalent numbers for comparison purposes, but are left as strings for addition (concatenation).