Skip to content

JavaScript Tutorial Variables and Values

JavaScript var and Hoisting

Lesson 12 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

Before ES2015, var was the only way to declare a variable. It still works, and you will see it in older code and tutorials, so you need to understand it. New code avoids it because of three behaviours that surprise people.

1. var ignores blocks

var has function scope, not block scope. A variable declared in an if or for block leaks out.

script.js
JS
if (true) {
  var leaked = "I escaped the block";
}
console.log(leaked); // → I escaped the block

With let, the last line would fail, which is usually what you want.

2. Hoisting

JavaScript moves var declarations to the top of their function before running the code. Only the declaration moves, not the value.

script.js
JS
console.log(city); // → undefined
var city = "Pune";
console.log(city); // → Pune

No error, just undefined. That quiet behaviour hides bugs. A let in the same place throws an error, which is easier to catch.

3. You can declare the same name twice

script.js
JS
var color = "red";
var color = "blue"; // no error
console.log(color); // → blue

Redeclaring by accident replaces a variable you meant to keep. let and const forbid this.

A classic bug: var in loops

script.js
JS
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0); // → 3, 3, 3
}

By the time the timers run, the single shared i is 3. With let i each pass gets its own copy and you see 0, 1, 2. This is a good example of why modern code avoids var.

So is var forbidden?

No. It still works in every browser, and a lot of existing code relies on it. Just prefer const and let in new code. When you read old code, treat var as “a let with odd scope rules”.

warning
Global var attaches to window
A var at the top level of a classic script becomes a property of window in browsers, which can clash with other scripts. let and const do not.