Page 2 of 4
"I am a string"
or
'I am a string'
Note that double or single quotes are acceptable; unlike some languages, such as Perl, JavaScript makes no distinction between the two forms of quote marks. This working example shows how to place a string into a variable:
MyVar = "This is JavaScript";
Boolean values in variables
There are two Boolean values: true and false. Some programming languages don't have a separate set of Boolean values, and
instead use 0 for false, and 1 or -1 (or any other non-zero value) for true. JavaScript can use these numbers to represent
true and false but, in addition, reserves the words "true" and "false" to mean Boolean true and false. You can think of the
Boolean true and false values as being equivalent to on/off or yes/no. To assign a Boolean value to a variable, provide just
the word true or false, without quotes. Here's an example:
MyVar = true;
Objects in variables
Variables can contain objects, including JavaScript objects. There are basically two kinds of object variables:
To assign a JavaScript object to a variable, provide the name of the object, as in:
MyVar = navigator;
To assign a new copy of a user-defined object to a variable, use the new statement, and provide the name of the object function:
MyVar = new myObject();
When it comes to the names you can give variables, JavaScript offers a great deal of latitude. JavaScript variables can be almost unlimited in length, although for practical reasons you'll probably keep your variable names under 10 or 15 characters. Shorter variable names help JavaScript execute the program faster. Keep the following in mind when naming your variables:
Unlike some other programming languages, in JavaScript there is no need to explicitly define the type of variable you want to create. This JavaScript behavior is called "loose data typing," and it differs from C and Java, both of which use strict data typing.
In JavaScript there is no need to differentiate variable types by appending special characters to the end of the variable name, such as MyVar$ for a string variable (or, for that matter, $MyVar for a scalar variable, a la Perl). JavaScript internally decodes the variable type based on its content.