Skip to main content
The var statement declares a function-scoped, module-scoped, or globally-scoped variable, optionally initializing it to a value. It operates independently of block constructs and is processed during the creation phase of the JavaScript execution context.

Syntax

Scope Semantics

Variables declared with var are bound to the nearest enclosing function execution context. If declared outside of any function, their binding depends on the execution environment: in traditional scripts, they are bound to the global execution context, whereas in ES6 modules or Node.js CommonJS modules, they are bound to the module execution context.
  • Function Scope: A var declared within a function is inaccessible outside of that function’s lexical environment.
  • Module Scope: A top-level var declared within an ES module or CommonJS module is scoped strictly to that module’s environment record, not the global environment.
  • Lack of Block Scope: Unlike let and const, var ignores block boundaries (such as those created by if, for, or while statements). A var declared inside a block is scoped to the containing function, module, or global environment.

Hoisting and Initialization

During the compilation phase, JavaScript engines hoist var declarations to the top of their enclosing function, module, or global scope.
  • Declaration Hoisting: The identifier is registered in the environment record before any code is executed.
  • Default Initialization: Hoisted var variables are automatically initialized with the primitive value undefined. The actual assignment expression remains in its original location and is evaluated during the execution phase.

Redeclaration

The JavaScript engine permits multiple var declarations with the same identifier within the same scope. Subsequent declarations are treated as re-assignments if they include an initializer; otherwise, the duplicate declaration is ignored. Strict mode ("use strict") does not prevent var redeclaration.

Global Object Binding and Modules

When executed in a traditional global script scope, a top-level var declaration creates a property on the global environment object (e.g., window in browsers, global in Node.js). This property is created with its [[Configurable]] attribute set to false, meaning it cannot be deleted via the delete operator. Crucially, this behavior does not apply to ES modules or Node.js CommonJS modules. Top-level var declarations inside a module do not create properties on the global object.
Tired of Poor JavaScript Skills? Fix That With Deep Grasping!Learn More