loading...

ES6 Part 1 var/let

scdan0624 profile image SCDan0624 ・2 min read

Intro
In 2015 Javascript added a lot of new features to their language. This version of Javascript is called ES6 and we will go over some of the new features of ES6 in this article

key word let
Normally in JS when declaring a variable we use the var keyword. The problem with using var is that it can be overwritten very easily.

var dog = "Fido"
var dog = "Lassie"
console.log(dog) // Lassie
Enter fullscreen mode Exit fullscreen mode

To solve this problem ES6 introduced the let keyword. If we use let with the same example an error will be triggered

let dog = "Fido"
let dog = "Lassie"
console.log(dog) // triggers an error
Enter fullscreen mode Exit fullscreen mode

By using the let variable you prevent accidentally changing variables when dealing with larger projects.

Scope
When declaring a variable with var you it is declared either globally or locally if declared inside a function.

With let you get the same functionality with an added bonus. If you declare a variable with let inside a block, expression, or statement it will be limited to that block, expression, or statement.

For example let's look at the declaring i in a for loop using both keywords.

var printFive;
for (var i = 0; i < 9; i++) {
  if (i === 5) {
    printFive = function() {
      return i;
    };
  }
}
console.log(printFive());
// returns 9
Enter fullscreen mode Exit fullscreen mode

Because the value of i was updated and printFive returns the global i and not the value of i we get 9 instead of 5.

By using the let keyword i is not defined because it was not declared in the global scope. It is only declared within the for loop statement.

let printFive;
for (let i = 0; i < 9; i++) {
  if (i === 5) {
    printFive = function() {
      return i;
    };
  }
} 
console.log(printFive());
// returns 9
Enter fullscreen mode Exit fullscreen mode

That concludes part 1 of ES6 in the next ES6 article we will go over the const keyword.

Discussion

pic
Editor guide