ES6: Introduction

ES6: Introduction

February 29, 2020

var vs let vs const

In this article, var, let and const will be discussed with respect to their scope, use and hoisting. Normally in Javascript we create a variable like this.

var x 	= "StatelyWorld!";

But in ES6 we can also create a variable like this.

let x 	= "StatelyWorld!";
const x = "StatelyWorld!";

Now you are wondering what is the use of let and const in ES6. First, let’s find the answer of why. There is a concept in JavaScript, called “Hoisting“. Hoisting is JavaScript’s default behavior of moving declarations to the top. Let’s look at a quick example to explain it.

(function(){
	var a = 1;
	var b = 2;
	console.log(a + " " + b);
})();

Output:

1 2

once it runs, it prints 1 and 2 as expected. but let’s move up line number 4 and we get below output.

(function(){
  var a = 1;
  console.log(a + " " + b);	
  var b = 2;  
})();

Output:

1 undefined

Now when someone uses this code in large projects probably by mistake because clearly console.log(a + ” ” + b); takes place before b is declared. However, this is perfectly valid javascript and it generates no error. This is the problem with hoisting in javascript. This code actually trend leads to something like this.

(function(){
  var a;
  var b;
  a = 1;
  b = 2;      
})();

Transpiling and Polyfilling

Polyfill – emulates APIs (AKA shimming)
Traspiler – trasforms your code

Leave A Comment