Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript var Statement

JavaScript var Statement

JavaScript Statement Reference JavaScript statement reference manual

Example

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

var carName = "Volvo";

Try it »

The bottom of this article contains more examples.


Definition and Usage

The var statement is used to declare variables.

Creating a JavaScript variable is also referred to as "declaring" a variable:

var carName;

After declaration, a 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 declaring it:

var carName = "Volvo";

For more information about variables, see our JavaScript Variables Tutorial JavaScript Scope the tutorial.


Browser support

Statement
var Yes Yes Yes Yes Yes

Syntax

var

varname

=

value

;

Parameter value

Parameters Description
varname Required. Specifies the variable name.

A variable name can contain letters, digits, underscores, and the dollar sign.

  • A variable name must start with a letter
  • A variable name can also start with $ and _ (though this is generally not recommended)
  • 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.
     **注意:** 如果变量声明未指定值,其默认值为 **undefined** |
    
    

    Technical Details

    JavaScript version: 1.0

    More examples

    Example

    Creates 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 »

    Example

    You can declare multiple variables in a single statement.

    The statement starts with var and variables are separated by commas:

    var lastName = "Doe",

    age = 30,

    job = "carpenter";

    Try it »

    Example

    Using variables in a loop:

    var text = "";

    var i;

    for (i = 0; i < 5; i++) {

        text += "The number is " + i + "
    ";

    }

    Try it »


    Related pages

    JavaScript tutorial: JavaScript Variables

    JavaScript tutorial: JavaScript Scope


    JavaScript Statement Reference JavaScript statement reference manual