Kunwar-Pratap
Published on

Difference between let, var, and const

Authors
let-var-const-banner

Introduction

In JavaScript, var, let, and const are all used to declare variables, but they behave differently. var is an older way to declare variables. It has function scope, meaning it's accessible throughout the entire function where it's declared, or it's global if declared outside of any function. It can be redeclared and reassigned.

In JavaScript, let, var, and const are used for variable declaration, but they have some key differences in terms of scope, reassignment, and immutability.

Firstly, var is the oldest way of declaring variables in JavaScript. Variables declared with var have function scope or global scope, depending on where they are declared. This means they are accessible throughout the function they are declared in, or globally if declared outside of any function.

For example:

function exampleFunction() {
    var x = 10;
    console.log(x); // Outputs: 10
}
console.log(x); // Throws ReferenceError: x is not defined

Here, x is accessible within the exampleFunction() because it was declared with var.

On the other hand, let and const were introduced in ECMAScript 6 (ES6) and have block scope, meaning they are only accessible within the block they are declared in (usually within curly braces ). Additionally, variables declared with let and const are not hoisted to the top of their containing block like var declarations are.

For example:

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

In this example, y is only accessible within the if block because it was declared with let.

The difference between let and const lies in reassignment. Variables declared with let can be reassigned, while variables declared with const cannot be reassigned after they are initialized. However, it's important to note that with complex data types like arrays and objects, the values inside them can be mutated even if the variable is declared with const.

For example:

let z = 30;
z = 40; // Valid reassignment with let
console.log(z); // Outputs: 40

const PI = 3.14;
PI = 3.14159; // Throws TypeError: Assignment to constant variable

In this example, z can be reassigned with let, but attempting to reassign PI with const throws an error.

Share this post

Loading reactions...