Assigning multiple variables
The above is a more compact equivilent of this:var b = a; var c = b;
Here's an example where all three variables are assigned initially with the string "AAA" and then the values of each are written out to the current page using document.write:var c = b = a = 'AAA'; document.write("a: " + a + "<br />" + "b: " + b + "<br />" + "c: " + c + "<br />");
The resulting output on the page would look like this:a: AAA b: AAA c: AAA
Any subsequent updates to any of the variables will not affect the other assigned variables. In the next example a, b and c are again initialised with "AAA" and then b is changed to "BBB".var c = b = a = 'AAA'; b = 'BBB'; document.write("a: " + a + "<br />" + "b: " + b + "<br />" + "c: " + c + "<br />");
The output from this example would be:a: AAA b: BBB c: AAA
- 3 minutes to read
You use variables to store, retrieve, and manipulate values that appear in your code. Try to give your variables meaningful names to make it easy for other people to understand what your code does.
The first time a variable appears in your script is its declaration. The first mention of the variable sets it up in memory, so you can refer to it later on in your script. You should declare variables before using them. You do this using the keyword.
If you do not initialize your variable in the statement, it automatically takes on the value .
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:
Here are some examples of invalid variable names:
When you want to declare a variable and initialize it, but do not want to give it any particular value, assign it the value . Here is an example.
If you declare a variable without assigning a value to it, it has the value . Here is an example.
The value behaves like the number 0, while behaves like the special value (Not a Number). If you compare a value and an value, they are equal.
You can declare a variable without using the 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.
If you add a number and a string, the number is coerced to a string.
If you add a Boolean and a string, the Boolean is coerced to a string.
If you add a number and a Boolean, the Boolean is coerced to a number.
In the following example, a number added to a string results in a string.
Strings are automatically converted to equivalent numbers for comparison purposes. To explicitly convert a string to an integer, use the parseInt function. To explicitly convert a string to a number, use the parseFloat function.