The Difference Between Function and Block Scope in JavaScript

Back to the basics with the var, let and const variables

Joe Cardillo
Jun 5, 2018 · 3 min read

The difference between var, let and const variables

var width = 100;
let height = 200;
const key = 'abc123';

var

// Define the variable:
var width = 100;
// Call the variable:
width;
// It returns:
100
// Reassign the variable and call it again:
width = 200;

width;
// Returns:
200
function setWidth(){
var width = 100;
console.log(width);
}
width;
// Returns:
Uncaught ReferenceError: width is not defined

Understanding scope

Example: var age = 100;
if (age > 12){
var dogYears = age * 7;
console.log(`You are ${dogYears} dog years old!`);
}
100
You are 700 dog years old!
dogYears;
// returns:
700

Benefits of using let and const

var age = 100;
if (age > 12){
let dogYears = age * 7;
console.log(`You are ${dogYears} dog years old!`);
}

Recap

var is function scope.
let and const are block scope.
Function scope is within the function.
Block scope is within curly brackets.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store