Difference between var and let keywords in JavaScript

 Difference between var and let keywords in JavaScript

Everything you've studies till now till section 4 was ES5. Beginning for this section, you will learn ES6 concepts.

Let's begin by checking the differences between var and let keywords. Both of these are used to declare variables, however they are different. The main difference is usually unnoticeable but it's good to know it.

Let's look at an example. Assuming you create a variable a, and you recreate it, there's no error.

    <script>
        var a = 10var a = 25;
        console.log(a);
        //let b = 2; let b = 10;
        //console.log(b);
    </script>

However, if we use the let keyword and try doing this, it will throw and error for us.
Error: "Identifier 'b' has already been declared"

    <script>
        let b = 2let b = 10;
        console.log(b);
    </script>

That's one of the major difference. This will ensure the variables are not overwritten by mistake. The keyword let was created to overcome the limitation of var keyword.
Note: There is a difference between assignment and overwriting variables.

Scope example borrowed from freeCodeCamp. In this example we are looking at function and block scope of i variable inside the function.

function checkScope() {
  "use strict";
  let i = "function scope";
  if (true) {
    let i = "block scope";
    console.log("Block scope i is: "i);
  }
  console.log("Function scope i is: "i);
  return i;
}

Other differences:

  • var variables have global scope and let variables have a block scope
  • var variables are initialized to undefined. let variables are not initialized. If you reference a unutilized let, you will get a ReferenceError.
  • Global var variables are added to global objects as properties. E.g. window.a works.



Post a Comment

0 Comments

React