The Difference Between Function and Block Scope in JavaScript

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

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.

Coding, creativity, music, and books. Pianist & composer — @vontmer

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