Search⌘ K
AI Features

var vs let

Explore the differences between var and let declarations in JavaScript, focusing on function scope, block scope, hoisting, and the temporal dead zone. Understand how these concepts affect variable accessibility and error handling to write clearer, safer code.

We'll cover the following...

Variables declared with var have function scope. This means that they are accessible inside the function/block they are defined in. Take a look at the following code:

Node.js
var guessMe = 2;
console.log("guessMe: "+guessMe);// A: guessMe is 2
( function() {
console.log("guessMe: "+guessMe);// B: guessMe is undefined
var guessMe = 5;
console.log("guessMe: "+guessMe);// C: guessMe is 5
} )();
console.log("guessMe: "+guessMe);// D: guessMe is 2

Comment B may surprise you if you have not heard of hoisting. If a variable is declared using var inside a function, the Javascript engine treats them as if they are declared at ...