JavaScript varStatement

JavaScript 语句参考手册JavaScript Statement Reference

Examples

Create a variable named carName with the value "Volvo":

var carName = "Volvo";

Try it Yourself »

More examples are included at the bottom of this article.


Definition and Usage

The var statement is used to declare variables.

Creating a JavaScript variable is also called "declaring" a variable:

var carName;

After a variable is declared, the variable is empty (has no value).

To assign a value to a variable, do the following:

carName = "Volvo";

You can also assign a value to a variable when you declare it:

var carName = "Volvo";

For more information about variables, please refer to ourJavaScript VariablesTutorialJavaScript ScopeTutorial.


Browser Support

Statement
var Yes Yes Yes Yes Yes


Syntax

var varname = value;

Parameter Values

Parameter Description
varname Required. Specifies the variable name.

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

  • Variable names must begin with a letter
  • Variable names can also begin with $ and _ (but this is generally not used)
  • Variable names are case-sensitive (y and Y are different variables)
  • Reserved words (such as JavaScript keywords) cannot be used as variable names
value Optional. Specifies the value of the variable.

Note:If a variable is declared without a specified value, its default value isundefined

Technical Details

JavaScript Version: 1.0


实例s

More Examples

Examples

Create two variables x and y. Assign 5 to x and 6 to y. Then output the result of x + y:

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

Try it Yourself »

Examples

You can declare multiple variables in one statement.

The statement begins withvarand variables are separated by commas:

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

Try it Yourself »

Examples

Use variables in a loop:

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

Try it Yourself »


Related Pages

JavaScript Tutorial:JavaScript Variables

JavaScript Tutorial:JavaScript Scope


JavaScript 语句参考手册JavaScript Statement Reference Other Extensions