No particular character identifies a variable in JavaScript, the way
the dollar sign ($
) does in PHP.
Instead, variables use the following naming rules:
A variable may include only the letters a-z
, A-Z
,
0-9
, the $
symbol, and the underscore (_
).
No other characters, such as spaces or punctuation, are allowed in a variable name.
The first character of a variable name can be only a-z
, A-Z
,
$
, or _
(no numbers).
Names are case-sensitive. Count
, count
, and COUNT
are all different variables.
There is no set limit on variable name lengths.
And yes, you’re right, that is the $
there in that list. It is
allowed by JavaScript and may be the first character
of a variable or function name. Although I don’t recommend keeping the
$
s, this does mean that you can port a
lot of PHP code to JavaScript quickly.
JavaScript string variables should be enclosed in either single or double quotation marks, like this:
greeting = "Hello there" warning = 'Be careful'
You may include a single quote within a double-quoted string or a double quote within a single-quoted string, but a quote of the same type must be escaped using the backslash character, like this:
greeting = "\"Hello there\" is a greeting" warning = '\'Be careful\' is a warning'
To read from a string variable, you can assign it to another one, like this:
newstring = oldstring
or you can use it in a function, like this:
status = "All systems are working" document.write(status)
Creating a numeric variable is as simple as assigning a value, like these examples:
count = 42 temperature = 98.4
Like strings, numeric variables can be read from and used in expressions and functions.
JavaScript arrays are also very similar to those in PHP, in that an array can contain string or numeric data, as well as other arrays. To assign values to an array, use the following syntax (which in this case creates an array of strings):
toys = ['bat', 'ball', 'whistle', 'puzzle', 'doll']
To create a multidimensional array, nest smaller arrays within a larger one. So, to create a two-dimensional array containing the colors of a single face of a scrambled Rubik’s Cube (where the colors red, green, orange, yellow, blue, and white are represented by their capitalized initial letters), you could use the following code:
face = [ ['R', 'G', 'Y'], ['W', 'R', 'O'], ['Y', 'W', 'G'] ]
The previous example has been formatted to make it obvious what is going on, but it could also be written like this:
face = [['R', 'G', 'Y'], ['W', 'R', 'O'], ['Y', 'W', 'G']]
or even like this:
top = ['R', 'G', 'Y'] mid = ['W', 'R', 'O'] bot = ['Y', 'W', 'G'] face = [top, mid, bot]
To access the element two down and three along in this matrix, you would use the following (because array elements start at position zero):
document.write(face[1][2])
This statement will output the letter O
for orange.
JavaScript arrays are powerful storage structures; Chapter 15 discusses them in much greater depth.