var vs let vs const in JavaScript

Hello Folks!

There are mainly 3 keywords that can be used to define a variable in javascript. Let's learn what are the differences between the three of them.

Defining Variable

JavaScript has three ways to declare variables namely, var, let, and const:

var -> Oldest Keyword

let -> Introduced in ES6

const -> Introduced in ES6

Assignment

var and let can be reassigned to a new value.

var a = "Jagadish"
a = "Patil"

console.log(a); // "Patil"
let a = 5
a = 8

console.log(a); // 8

const keyword variables are constant values that cannot be changed or reassigned to a new variable.

const KEY = 123
KEY = 456 // => TypeError: Assignment to constant variable.
const KEY = 123
var KEY = 456 // => TypeError: Assignment to constant variable.

Scope

Scope means it determines the accessibility (visibility) of the variables.

var -> globally / function-scoped

let -> block-scoped

const -> block-scoped

Scope Comparison

Function Scoped - Function scoped means they are only available inside the function they are created in and if it is not created inside the function then they are called globally scoped.

Block Scoped - Block scoped means a block of code that is the code between curly braces in JavaScript (any code within { } braces).

Scope Example

Function Scoped

function myNumber() {
    var a = 1 // => variable scoped to myNumber()
    if (true) {
        var a = 2 // => variable overrided the value of a = 1 to a =2
        console.log(a); // => 2
    }
    console.log(a); // => 2
}

Block Scoped

function myNumber() {
    let a = 1 // => variable scoped to myNumber()
    if (true) {
        let a = 2 // => variable not conflict with a = 1
        console.log(a); // => 2
    }
    console.log(a); // => 1
}

Behaviour

  • var -> var variables can be updated and re-declared within their scope.

  • let -> let variables can be updated but not re-declared.

  • const -> const variables can neither be updated nor re-declared.

Hoisting

Hoisting in JavaScript is a behavior in which a variable or a function can be used before declaration.

var is always hoisted to the top of their respective scope.

x = 20
var x

console.log(x); //=> 20

let and const are also hoisted but will throw an error if the variable is used before declaration.

x = 20
let x

console.log(x); //=> ReferenceError: x is not defined

That's it for now. We have seen some major differences between the var, let, and const keywords.

I am hoping that you find this post is useful, and Thank you for reading.

Keep Exploring!