let var and const | what is the difference?

let var and const | what is the difference?


Introduction

First what is these terms, let, var and const? Let's learn. These terms are used in JavaScript. These 3 terms function like variables actually. However, these terms have their own specialities which we will study in-depth in this article

Var

In 2015, an update to JavaScript was introduced to bring the term called let. However, before that var was used commonly. Var actually means variable .

Var is used as a global scoped variable when it needs to be declared outside of a function and is scoped when it's declared in a function.

Here's an example:

    var test = "Welcome!";
   
    function myFunction() {
        var world = "world";
    }

In this example, variable test is globally scoped as it's out of the function.
So we can't access variable world outside of the function. Instead, if we do:

var test = "Welcome";
   
    function myFunction() {
        var world = "world";
    }
    console.log(hello); // error: variable world is not defined

We'll get an error because variable world is outside of the function.

Let

Let came in the 2015 ES6 JavaScript update. Let is preferred for variable declaration. Let is also better than var. Let's learn about let.

Let is block scoped. This means let is only allowed to use within one block. A block is known as piece of code in the curly bracket symbol { } .

For an example:

let test = "Welcome";
   let times = 4;

   if (times > 3) {
        let world = "World";
        console.log(hello);// "say World instead"
    }
   console.log(hello) // Error: World is not defined

In this case, since world is outside its block, it returns an error. This is because let variables are block scoped as mentioned earlier.

Const
Const exists for quite some time too. Const actually stands for constant . Const shares some similarities with let anyhow. Const declarations are also block scoped like let. However, let can be updated but const can't be updated too.

For example, in let we can do:

let test = "Welcome";
    test = "World";

But in const, we can't do that too. Thus, every const declaration must be done at the time of declaration itself.

However, the behavior is different when objects are declared with const. A const object can't be updated but the const object properties can be updated like below:

 const test = {
        message: "Welcome",
        times: 4
    }

Now here's a quick summary on the differences incase you're still confused.

Credits: constletvar.com


And that's all the differences between let, var and const!

Post a Comment

Previous Post Next Post