Students Empire

Learn Something New
Home

Variable Introduction


ECMAScript variables are loosely typed.

A variable can hold any type of data. A variable is a named placeholder for a value.

To define a variable, use the var operator followed by the variable name, like this:

				var message; 
				

This code defines a variable named message that can be used to hold any value. Without initialization, it holds the special value undefined.

You can define the variable and set its value at the same time:

var message = "hi"; 

Initialization doesn't mark the variable as being a string type.

You can not only change the value stored in the variable but also change the type of value, such as this:

				var message = "hi"; 
				message = 100;      //legal, but not recommended
				

In this example, the variable message is first defined as having the string value "hi" and then overwritten with the numeric value 100.

It's not recommended to switch the data type that a variable contains, it is completely valid in ECMAScript.