Skip to content

var

In JavaScript, the var keyword declares a variable that’s scoped to the nearest enclosing function or class static block, or to the script or module when neither contains it. Blocks such as if statements and loop bodies don’t limit a var binding, which sets it apart from let and const.

A var binding is created and set to undefined when its scope starts, before any code in that scope runs, and the initializer assigns the value only when execution reaches it. That’s why var declarations behave the way they do under hoisting.

Declaring the same name twice with var isn’t an error, even in strict mode, but a var can’t share a scope with a let or const of the same name. At the top level of a script, var also creates a property on the global object that delete can’t remove. var has been part of the language since the first edition of ECMAScript.

JavaScript var Keyword Syntax

A var declaration has the following form:

Language: JavaScript Syntax
var <name> [= <value>][, <name2> [= <value2>], ...];

The name can also be a destructuring pattern, which needs an initializer. Without an initializer, the declaration assigns nothing, so a redeclared binding keeps its current value.

JavaScript var Keyword Examples

A var declaration belongs to the whole function, not to the block it appears in:

Language: JavaScript
> function findLastPositive(numbers) {
…   for (var i = 0; i < numbers.length; i++) {
…     if (numbers[i] > 0) {
…       var lastPositive = numbers[i];
…     }
…   }
…   return [i, lastPositive];
… }
undefined
> findLastPositive([3, -1, 7, -2])
[ 4, 7 ]

Both i and lastPositive belong to the whole function body, so they’re still readable after the loop and the if block end.

Reading a var binding before its declaration runs gives undefined instead of throwing:

Language: JavaScript
> function describe() {
…   const before = status;
…   var status = "ready";
…   return [before, status];
… }
undefined
> describe()
[ undefined, 'ready' ]

JavaScript var Keyword Use Cases

  • Declaring variables in legacy code that predates let and const
  • Sharing one binding across every block of a function body
  • Creating a global object property from a top-level script declaration
  • Reading code that relies on var hoisting or redeclaration

Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.


By Leodanis Pozo Ramos • Updated Nov. 4, 2026