Skip to main content Accessibility Feedback

let, const, and block scoping in JavaScript

On Monday, we looked at the difference between let, const, and var (and why you should mostly just use let). Yesterday, we learned how scope works.

Today, we’re going to combine these topics and look at block scoping in JavaScript. Let’s dig in!

What is block scoping?

In JavaScript, a block is anything that appears between a set of curly brackets ({}).

// This is in the global scope
let answer = null;
let question = false;

// This is a block
if (question === true) {

	// This in a block scope
	let answer = 42;


let and const behave differently than var with block scope

The let and const keywords provide block-scoping. The var keyword does not.

That means that if you declare a variable with var, then use var to declare another variable with same name inside a block scope, the original variable will be updated. If you use let or const, a new variable contained within the block scope is created.

var sandwich = 'tuna';
let drink = 'soda';

if (true) {

	// drink is in the block scope, but sandwich is not
	var sandwich = 'turkey';
	let drink = 'water';

	// logs "turkey"

	// logs "water"


// logs "turkey"

// logs "soda"

Because let and const provide block-scoping, they are almost always a better choice than var.