Var vs Let vs Const in JavaScript

codesplash
2 min readApr 19, 2024

--

#5 JavaScript Series

On the Basis of Scope:

var

var is function scoped & Hoisted to the top of its function or global scope.

Can be reassigned and redeclared within its scope.

If declared within a block (e.g., if statement), it’s still visible outside the block.

Example:

function example() {
if (true) {
var x = 10;
console.log(x); // Outputs: 10
}
console.log(x); // Outputs: 10
}
example();

let

Scope: Block-scoped

Hoisted to the top of its block, but not initialized.

Cannot be redeclared within the same scope.

Can be reassigned within its scope.

Example:

function example() {
if (true) {
let y = 20;
console.log(y); // Outputs: 20
}
console.log(y); // Throws ReferenceError: y is not defined
}
example();

const

Scope: Block-scoped

Hoisted to the top of its block, but not initialized.

Cannot be reassigned after declaration.

Example:

function example() {
const z = 30;
z = 40; // Throws TypeError: Assignment to constant variable
}
example();

While a variable declared with const cannot be reassigned to a new value, if it holds a reference to an object, the content of that object can be modified.

Example:

const arr = [1, 2, 3];
arr.push(4);
console.log(arr); // Outputs: [1, 2, 3, 4]

Variable Shadowing:

Variable shadowing occurs when a variable declared within a certain scope has the same name as a variable declared in an outer scope, thereby hiding the outer variable within that scope.

Example:

function example() {
let a = 10;
if (true) {
let a = 20; // Inner 'a' shadows outer 'a'
console.log(a); // Outputs: 20
}
console.log(a); // Outputs: 10 (outer 'a' remains unchanged)
}
example();

If both variables were declared using var instead of let, due to function scoping, both would print "20" since the inner 'a' would change the outer 'a', affecting both within the function scope.

Illegal shadowing:

Making let variables var.

Making const variables var.

function example() {
let a = 20;
const b = 40;
if (true) {
var a = 30; // Illegal shadowing of 'a'
var b = 50; // Illegal shadowing of 'b'
}
}
example();

Declaration:

var can be redeclared within the same scope, with the last declaration taking precedence.

let and const cannot be redeclared within the same scope; attempting to do so will result in a syntax error.

Example:

var a = 20;
var a = 50; // Valid: 'a' is redeclared

let b = 30;
let b = 40; // SyntaxError: Identifier 'b' has already been declared

const c = 40;
const c = 50; // SyntaxError: Identifier 'c' has already been declared

--

--

codesplash

Currently Moulding a New Life Through Coding || Follow me on linkedin codessmasherdeepjyotidas