Jump to content

ECMAScript variables

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Gwern (talk | contribs) at 17:23, 21 October 2006 (moved ECMAScript Variables to ECMAScript variables: decaps). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

Template:Linkless-date

ECMAScript Variables

Variables in ECMAScript are defined by using the var operator (short for variable), followed by the variable name, such as:

var test = "hi";

In this example, the variable test is declared and given an initialization value of "hi" (a string). Because ECMAScript is loosely typed, the interpreter automatically creates a string value for test without any explicit type declaration. You can also define two or more variables using the same var statement:

var test = "hi", test2 = "hola";

The previous code defines the variable test to have a value of "hi" and the variable test2 to have a value of "hola". Variables using the same var statement don’t have to be of the same type, however, as shown in the following:

var test = "hi", age = 25;

This example defines test (yet again) in addition to another variable named age that is set to the value of 25. Even though test and age are two different data types, this is perfectly legal in ECMAScript. Unlike Java, variables in ECMAScript do not require initialization (they are actually initialized behind the scenes, which I discuss later). Therefore, this line of code is valid:

var test;

Also unlike Java, variables can hold different types of values at different times; this is the advantage of loosely typed variables. A variable can be initialized with a string value, for instance, and later on be set to a number value, like this:

var test = 'hi';
alert(test); //outputs 'hi'
//do something else here
test = 55;
alert(test); //outputs '55'

This code outputs both the string and the number values without incident (or error). You can edit JavaScript by JavaScript editor. As mentioned previously, it is best coding practice for a variable to always contain a value of the same type throughout its use.