Difference between var and let in javascript ?

In this article, We’ll see what is the difference between var and let in javascript ?

Below an example will clarify the difference.




The var statement declares a variable, optionally initializing it to a value

Demo: Statement – Var

    var x = 1;

    if (x === 1) {
      var x = 2;

      console.log(x);
      // expected output: 2
    }

    console.log(x);
    // expected output: 2

The let statement declares a block scope local variable, optionally initializing it to a value.

Demo: Statement – Let

 let x = 1;

 if (x === 1) {
   let x = 2;

   console.log(x);
   // expected output: 2
  }

   console.log(x);
   // expected output: 1

let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.

Variables declared by let have as their scope the block in which they are defined, as well as in any contained sub-blocks. In this way, let works very much like var. The main difference is that the scope of a var variable is the entire enclosing function

That’s it!. Please share your thoughts or suggestions in the comments below.

Leave a Reply

Your email address will not be published. Required fields are marked *