Difference between var, let, and const in Javascript.

Dharvikkanagala
2 min readJun 6, 2021

Understanding Function scope vs. Block scope in Javascript

In Javascript, one can define variables using the keywords var, let, or const.

var a=10;
let b=20;
const PI=3.14;

var: A variable defined with the keyword “var” has a scope that is limited to the “function” it is defined in. The variable’s scope is global if it is defined outside of any function.

var is “function scoped”.

let: The scope of a variable defined with the keyword “let” or “const” is limited to the “block” defined by curly braces i.e. {}.

let” and “const” are“block-scoped”.

const: The scope of a variable declared with the keyword “const” is restricted to the curly braced block. However, if a variable is defined with keyword const, it cannot be reassigned.

const” cannot be re-assigned to a new value. However, it CAN be mutated.

Function scoped vs. Block scoped

In JavaScript, there’s two kinds of scope: function-scope and block-scope

Function-scope

function myFn()
{

var foo = 'peekaboo!';
console.log(foo); // 'peekaboo!'
}
console.log(foo); // ReferenceError: foo is not defined

Using var, variables are function-scoped because their visibility is limited to the function. When you try to use it outside of the function, you’ll get an error.

Block-scope

if (true)
{
var foo = 'peekaboo!';
let bar = 'i see u';
const baz = 'baby blue!';
console.log(foo); // 'peekaboo!';
console.log(bar);
// 'i see u';
console.log(baz); // 'baby blue!';
}
console.log(foo);
// 'peekaboo!';
console.log(bar); // ReferenceError: bar is not defined console.log(baz); // ReferenceError: baz is not defined

Notice the visibility isn’t limited by the if-statement block. However, both bar and baz are limited invisibility to the block of code.

Why would you chose “let” over “var”?

It is best not to declare variables as global variables when programming with Javascript. since the global variable might be accidentally modified from anywhere in the Javascript code. To avoid this, make sure the variables’ scope is limited to the code block where they must be executed.
Before the introduction of the keyword let as part of ES6, programmers utilized the IIFE pattern to avoid polluting the global namespace by avoiding the issue of variable scoping with var. The IIFE pattern is no longer required since the introduction of let, and the scope of the variable defined with let is now limited to the scope of the variable.

Summary

var is functional scope

let, const are both block scope

--

--