Latest web development tutorials

JavaScript var statement

JavaScript Statements Reference Manual JavaScript Statements Reference Manual

Examples

Create a variable, the variable named carName, a value of "Volvo":

var carName = "Volvo";

try it"

Bottom of this article contains more examples.


Definition and Usage

var statement to declare variables.

Create a JavaScript variable is also called the "declaration" a variable:

var carName;

After the variable declaration, the variable is empty (no value).

Copy variables, as follows:

carName = "Volvo";

When you declare a variable, you can also assign values ​​to variables:

var carName = "Volvo";

For more information about variables, please refer to our JavaScript variable tutorial JavaScript scope tutorial.


Browser Support

Statements
var Yes Yes Yes Yes Yes


grammar

var varname = value;

Parameter Value

parameter description
varname have to. Specifies the variable name.

Variable names can contain letters, numbers, underscores and dollar signs.

  • Variable names must begin with a letter
  • Variable name can also be the beginning and $ _ to (but generally did not use)
  • Variable names are case sensitive (y and Y are different variables)
  • Reserved word (such as JavaScript keywords) can not be used as variable names
value Optional. The value of the specified variable.

Note: If a variable declaration does not specify a value, its default value is undefined

technical details

JavaScript version: 1.0


Examples s

More examples

Examples

Create two variables x and. assignment x 5, y 6 assignment. And then outputs the result of x + y is:

var x = 5;
var y = 6;
. Document.getElementById ( "demo") innerHTML = x + y;

try it"

Examples

You can declare multiple variables in one statement.

Var statement to begin with, comma separated variable:

var lastName = "Doe",
age = 30,
job = "carpenter";

try it"

Examples

Using variables in the loop:

var text = "";
var i;
for (i = 0; i <5; i ++) {
text + = "The number is" + i + "<br>";
}

try it"


Related Pages

JavaScript Tutorials: JavaScript variable

JavaScript Tutorials: JavaScript Scope


JavaScript Statements Reference Manual JavaScript Statements Reference Manual