liveBook · Manning

Var

As explained in Secrets of the JavaScript Ninja, Third Edition

var is a JavaScript declaration keyword for creating a function-scoped binding that is initialized to undefined during scope setup.

var declares a binding scoped to the nearest function or module, ignoring intervening blocks. During scope setup, the binding is initialized to undefined, so it can be read before its declaration executes. section 7.3.1 section 7.3.2

Loop callbacks and scope

In a timer loop, replacing let i with var i means each callback sees the same binding; after the loop, each logs the final value. With let, each iteration has its own binding, so the callbacks log 0, 1, and 2. section 7.3.1

In practice:

  • Treat var as a legacy keyword; most modern JavaScript developers prefer const and let. section 7.3.1
  • Enforce avoiding var with ESLint’s no-var rule. section 7.3.1

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Defines var’s scope and undefined pre-initialization behavior, but largely omits it from worked code examples.
Examples
Contrasts a timer loop using let with the repeated final value expected when its counter uses var.
What you can do after
Understand how var scope and initialization differ from let and const.
How it connects
Connects var to function scope, block scope, let, const, closures, and hoisting.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.