let vs var in ecmascript 6

Let vs var the difference is scoping. let is scoped to the nearest enclosing block and var is scoped to the nearest function block (both are global if outside any block) , which can be smaller than a function block.Also, variables declared with let are not accessible before they are declared in their enclosing block.

ecma 6 let vs var

Global : 

let a = 'hello';  // globally scoped
var b = 'world'; // globally scoped

However, global variables defined with let will not be added as properties on the global window object like those defined with var.

console.log(window.a); // undefined
console.log(window.b); // 'world'

Redeclaration : 

Assuming strict mode, var will let you re-declare the same variable in the same scope. On the other hand, let will not.

'use strict';
let a = 'hello';
let a = 'world'; // SyntaxError: Identifier 'a' has already been declared

'use strict';
var a = 'hello';
var a = 'world'; // No problem, `a` is replaced.

ES6 lets you declare variables to belong to individual blocks (pairs of { .. } ), using the let keyword.

function foo() {
  var a = 1;
  if (a >= 1) {
    letb = 2;
    while (b < 5) {
      letc = b * 2;
      console.log(a + c);
// 5 7 9

Because of using let instead of var , b will belong only to the if statement and thus not to the whole foo() function’s scope. Similarly, c belongs only to the while loop. Block scoping is very useful for managing your variable scopes in a more fine-grained fashion, which can make your code much easier to maintain over time.

Here is the difference. let is only visible in the for() loop and var is visible to the whole function.

function somefunctionA() {
    //i is *not* visible out here

    for( let i = 0; i < 5; i++ ) {
        //i is only visible in here (and in the for() parentheses)
        //and there is a separate i variable for each iteration of the loop

    //i is *not* visible out here

function somefunctionB() {
    //j *is* visible out here

    for( var j = 0; j < 5; j++ ) {
        //j is visible to the whole function

    //j *is* visible out here

I hope you understand the let vs var with above example. please comment and share.

No comments:

Post a Comment

Download the eBook of react js for beginners

ReactJS basically is an open-source JavaScript library which is used for building user interfaces specifically for single page applications...