Easy Tutorial
❮ Jsref Indexof Met Console Log ❯

JavaScript var Statement

JavaScript Statements Reference

Example

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

var carName = "Volvo";

More examples are included at the bottom of this page.


Definition and Usage

The var statement is used to declare variables.

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

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

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

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

For more information on variables, see our JavaScript Variables tutorial and JavaScript Scope tutorial.


Browser Support

Statement Chrome Edge Firefox Safari Opera
var Yes Yes Yes Yes Yes

Syntax

Parameter Values

Parameter Description
varname Required. Specifies the variable name. The variable name can contain letters, digits, underscores, and dollar signs. The variable name must start with a letter. <br> The variable name can also start with $ and _ (but these are not commonly used). <br> Variable names are case-sensitive (y and Y are different variables). <br> Reserved words (like JavaScript keywords) cannot be used as variable names.
value Optional. Specifies the value of the variable. <br> <br> Note: If the variable declaration does not specify a value, it defaults to undefined.

Technical Details

| JavaScript Version: | 1.0 | | --- | --- |


More Examples

Example

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

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

Example

You can declare multiple variables in one statement.

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

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

Example

Using variables in a loop:

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

Related Pages

JavaScript Tutorial: JavaScript Variables

JavaScript Tutorial: JavaScript Scope

❮ Jsref Indexof Met Console Log ❯