You’re reading the English version of this content since no translation exists yet for this locale. Help us translate this article!

La sentència variable declara una variable, i de forma opcional pot inicialitzar-la amb un valor.


var varnom1 [= valor1 [, varnom2 [, varnom3 ... [, varnomN]]]];
El nom de la variable. pot ser qualsevol identificador legal.
Valor inicial de la variable. Pot ser qualsevol expressió legal.


Les declaracions de variables, sigui on sigui que ocorrin, són processades abans que cap codi sigui executat. L'abast d'una variable declarada amb var és el seut context d'execució actual, which is either the enclosing function or, for variables declared outside any function, global.

Assigning a value to an undeclared variable implicitly creates it as a global variable (it becomes a property of the global object) when the assignment is executed. The differences between declared and undeclared variables are:

1. Declared variables are constrained in the execution context in which they are declared. Undeclared variables are always global.

function x() {
  y = 1;   // Throws a ReferenceError in strict mode
  var z = 2;


console.log(y); // logs "1" 
console.log(z); // Throws a ReferenceError: z is not defined outside x

2. Declared variables are created before any code is executed. Undeclared variables do not exist until the code assigning to them is executed.

console.log(a);                // Throws a ReferenceError.
console.log('still going...'); // Never executes.
var a;
console.log(a);                // logs "undefined" or "" depending on browser.
console.log('still going...'); // logs "still going...".

3. Declared variables are a non-configurable property of their execution context (function or global). Undeclared variables are configurable (e.g. can be deleted).

var a = 1;
b = 2;

delete this.a; // Throws a TypeError in strict mode. Fails silently otherwise.
delete this.b;

console.log(a, b); // Throws a ReferenceError. 
// The 'b' property was deleted and no longer exists.

Because of these three differences, failure to declare variables will very likely lead to unexpected results. Thus it is recommended to always declare variables, regardless of whether they are in a function or global scope. And in ECMAScript 5 strict mode, assigning to an undeclared variable throws an error.

var hoisting

Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it's declared. This behavior is called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code.

bla = 2
var bla;
// ...

// is implicitly understood as:

var bla;
bla = 2;

For that reason, it is recommended to always declare variables at the top of their scope (the top of global code and the top of function code) so it's clear which variables are function scoped (local) and which are resolved on the scope chain.


Declarar i inicialitzar dues variables

var a = 0, b = 0;

Assignar dues variables amb un sol valor de tipus cadena

var a = "A";
var b = a;

// Equival a:

var a, b = a = "A";

Sigueu conscient de l'ordre:

var x = y, y = 'A';
console.log(x + y); // undefinedA

Aquí, tant x com y són declarats abans que cap codi sigui executat, l'assignació té loc després. en el moment que "x = y" s'avalua, y existeix de forma que no es llança cap ReferenceError i el valor és 'undefined'. Així doncs, a x se li assigna el vaor undefined. Then, y is assigned a value of 'A'. En conseqüència, després de la primera línia, x === undefined && y === 'A', com a resultat.

Inicialització de diverses variables

var x = 0;

function f(){
  var x = y = 1; // x és declarada de forma local, però y no!

console.log(x, y); // 0, 1
// x és la global, tal i com era d'esperar
// y tot i així s'ha filtrat fora de la funció! 

Implicit globals and outer function scope

Variables that appear to be implicit globals may be references to variables in an outer function scope:

var x = 0;  // x is declared global, then assigned a value of 0

console.log(typeof z); // undefined, since z doesn't exist yet

function a() { // when a is called,
  var y = 2;   // y is declared local to function a, then assigned a value of 2

  console.log(x, y);   // 0 2 

  function b() {       // when b is called
    x = 3;  // assigns 3 to existing global x, doesn't create a new global var
    y = 4;  // assigns 4 to existing outer y, doesn't create a new global var
    z = 5;  // creates a new global variable z and assigns a value of 5. 
  }         // (Throws a ReferenceError in strict mode.)

  b();     // calling b creates z as a global variable
  console.log(x, y, z);  // 3 4 5

a();                   // calling a also calls b
console.log(x, z);     // 3 5
console.log(typeof y); // undefined as y is local to function a


Especificació Estat Comentaris
ECMAScript 1st Edition (ECMA-262) Standard Definició inicial. Implementat en JavaScript 1.0
ECMAScript 5.1 (ECMA-262)
The definition of 'var statement' in that specification.
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'variable statement' in that specification.

Compatibilitat amb navegadors

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!

Característica Chrome Firefox (Gecko) Internet Explorer Opera Safari
Suport bàsic (Yes) (Yes) (Yes) (Yes) (Yes)
Característica Android Chrome per Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Suport bàsic (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

Vegeu també