Wednesday, 1 March 2017

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.

Featured post

How to create dynamic schema in mongodb

Sometime what we need in our application is to create mongodb schema for collection and some of our collection schema are same but names are...

Popular Posts