Variable Declarations - var let const
JavaScript has three keywords for declaring a variable:
constdeclares a variable that cannot be reassigned after its first value.letdeclares a variable that can be reassigned.varis the original keyword, from beforeletandconstarrived in ES2015. It still works, but it has rules that cause bugs.
The usual advice today is to use const by default, let when the value has to change, and var not at all in new code. The sections below show why.
Block scope against function scope
Section titled “Block scope against function scope”let and const are block-scoped, so they exist only inside the braces where they are declared. var is function-scoped, so it ignores blocks and is visible everywhere in the enclosing function:
function listTasks() { if (true) { var fromVar = 'var leaks out of the block'; let fromLet = 'let stays inside'; } console.log(fromVar); console.log(typeof fromLet);}
listTasks();This prints:
var leaks out of the blockundefinedThe difference matters most in loops. A let loop variable is a fresh variable on every pass, so a function created in the loop remembers the value from its own pass. A var loop variable is one variable shared by every pass, so every function sees its final value:
const withVar = [];for (var i = 0; i < 3; i++) { withVar.push(() => i);}
const withLet = [];for (let j = 0; j < 3; j++) { withLet.push(() => j);}
console.log(withVar.map((read) => read()));console.log(withLet.map((read) => read()));This prints:
[ 3, 3, 3 ][ 0, 1, 2 ]Redeclaring
Section titled “Redeclaring”var lets you declare the same name twice in one scope, and the second declaration quietly reuses the first variable:
var status = 'open';var status = 'closed';console.log(status);This prints:
closedlet and const refuse, which catches the mistake of reusing a name by accident:
let task = 'Buy milk';let task = 'Walk the dog';The file fails to load, before any line of it runs:
SyntaxError: Identifier 'task' has already been declaredDeclaring the same name in a nested block is still allowed, because that is a separate variable which shadows the outer one. Variable Scope shows shadowing.
Reassigning
Section titled “Reassigning”A let variable can be given a new value at any time. A const variable keeps the value it was declared with, and assigning to it throws a TypeError:
let visitors = 10;visitors = visitors + 5;console.log(visitors);
const maxVisitors = 50;try { maxVisitors = 60;} catch (err) { console.log(`${err.name}: ${err.message}`);}This prints:
15TypeError: Assignment to constant variable.const fixes the variable, not the value inside it, so the properties of a const object can still change. The Variable Declaration - const covers this.
Other differences
Section titled “Other differences”- Hoisting. A
varcan be read before its declaration line and givesundefined, while reading aletorconstthat early throws aReferenceError. Hoisting - var vs let explains why. - The global object. A top-level
varin a classic script becomes a property of the global object, and a top-levelletorconstdoes not. Global Variables/Properties, globalThis shows the difference.
Steve Griffith covers this topic in his video var let const - Variable Declarations in JavaScript.