var statement JS Home  <<  JS Reference  <<  var

In JavaScript you create a variable(s) using the keyword var, followed by the name(s) you wish to identify the variable(s) by. You can optionally assign an initial value at creation time.

Description

Declares a variable(s) that allows us to store some information that we may want to manipulate or use later. The variable is like a container where we put our information for later retrieval.

  • Variable scope is the current function for variables declared within a function, or the current application for variables declared outside a function.

Syntax

Signature Description
var aVariable [= aValue [, bVariable ... [, NVariable]]]];Declares a variable(s) that allows us to store some information that we may want to manipulate or use later. The variable is like a container where we put our information for later retrieval.

Parameters

Parameter Description
aValueCan be any legal identifier as outlined below:
  • Only letters, numbers, the dollar ($) and underscore (_) symbols are allowed when creating variable names.
  • Only letters, the dollar ($) and underscore (_) symbols are allowed as the first character of the variable name.
  • Variable names are case sensitive.
  • Do not use keywords for variable names.
NVariableAn initial value which can be any legal expression.

Examples

The code below creates two undefined variables called aVariable and bVariable.


var aVariable;
var bVariable;

Creates a variable called aVariable and assigns the value 25 to it. Creates a variable called bVariable and assigns the value 'candles' to it and the concatenates the two variables for display.



var aVariable = 25;
var bVariable = 'Candles';

alert(aVariable + bVariable);

Press the button below to action the above code:

You can also create multiple variables at the same time by delimiting the end of each variable name with the comma (,) symbol.



// Create three variables.
var aVariable, bVariable, cVariable;

// Create three variables with initial value of 0.
var aVariable = 0, bVariable = 0, cVariable = 0;

Press the button below to action the above code:

Related Tutorials

JavaScript Basic Tutorials - Lesson 5 - Variables