ECMA Script 6 variable declaration with var, let & const - let vs var

Sun Aug 16 2015

Paul Shan

JavaScript (and some other loosely typed languages) is popular for having only one data type; i.e. var. We declare everything with var in JavaScript; even the functions. So, why there is a need to redefine few things about variable declarations? What are the new features ECMA Script 6 want to provide us in variable declarations? This post contains the answer of these questions. We all know about var; and to make ES6 backward compatible TC39 (the technical committee to decide ECMA Script roadmaps) decides to make no changes on var. Thus var remains as it is and we are skipping the description of var.

Introduction to let

let is the newly added keyword in ECMA Script 6; will be implemented in JavaScript 1.7 which has already been started getting updated in some of the browsers.

Block Scoped

This is probably the main reason why we have let today. var is not blocked scoped. But as per the requirement of the programming community, variables should have been blocked scoped. People are more habituated to blocked scoped than function scoped. let is completely block scoped.
function func() {
    if (true) {
      var myVar = 100;
        let myLet = 200;
    }
    console.log(myVar); // 100
    console.log(myLet); // ReferenceError: myLet is not defined
}

Temporal dead zone : No hoisting

Temporal dead zone of a variable is that part of the program where that particular variable is not accessable in the scope. In case of var we had hoisting; for what var never had a temporal dead zone. But let is not similar to that.
function func() {
    if (true) {
      console.log(myVar); // 100
      console.log(myLet); // ReferenceError: myLet is not defined

      var myVar = 100;
        let myLet = 200;
    }
}

In case of let, the variable is completely unaccessible till the time the control reaches the line of declaration.

No multiple declaration

In case of var it doesn't matter how many time you try to declare it in a single scope (as hoisting makes things right). But in case of let, you can't.
function func() {
    if (true) {
      var myVar = 100;
        let myLet = 200;

      var myVar = 100; // OK
        let myLet = 200; // Error: already declared
    }
}

If the function has a parameter named "myParam", you cant declare myParam again inside the function with let.

In loops it gets fresh binding

After the last point if you start thinking if you can declare a variable with let in a loop; than don't worry, you can. In loops let gets a fresh binding in each iteration; thus you are free to go. But remember unlike var, the let variable can not be accessed from outside the loop
function func() {
  let arr = [];
  for (let i=0; i < 3; i++) {
      arr.push(i);
  }
  console.log(arr); // [0,1,2]
  console.log(i); //Error: not defined. If i was a var, the value would have been 3 here
}

Global variables

Again unlike var, if you declare a variable with let in the global scope, it will not become the part of the global object (window in browsers, global in Node.js).
var myVar = 100;
console.log(window.myVar); // 100

let myLet = 200;
console.log(window.myLet); //Undefined

Introduction to const

Just as let, const is also block scoped, has temporal dead zone and no multiple declaration allowed, similar behavior in global scope. However, it can not be used in loops as let can be used (shown in the last point of let).
function func() {
  let arr = [];
  for (const i=0; i < 3; i++) { //Error: "i" is read-only
      arr.push(i);
  }
  console.log(arr); // [0,1,2]
}

Read only

const creates immutable variables. You can assign the value only once.
function func() {
    const myConst = 100;
    myConst=200; //Error: read only
}

No blank declaration

Unlike let, you can't declare a const without assigning a value. It is mandatory to initialize it while declaring.
function func() {
    const myConst; //Error
}

Only the identifier itself is read only

Though it seems if an object is defined with const, none of it's property should be editable; but in practical only the identifier itself is read only. You can edit the properties of the object.
function func() {
  const me = {};
  me.name = "Paul"; //OK

  const people=[];
  people.push({}); //OK

  me = {}; //Error: read only
  people = [1,2,3]; //Error: read only
}

How to make the whole object immutable

function func() {
  const me = Object.freeze({});
  me.name = "Paul"; //Error

  const people=Object.freeze([]);
  people.push({}); //Error
}

var vs let

var let
Scope Function scoped Block scoped
Multiple declaration in the same scope No issues Throws error
Temporal dead zone No Yes
Access outside loop Yes No
Declaration conflict with function params No Yes
Global scope Exists in global scope as well as become a property of the global object. Exists in global scope but doesn't become a property of the global object.
 

More on variable declarations

Beyond just newly added keywords there are few more things you would like to know about ES6 variable declarations which will make you happy.

Object destructuring

function func () {
  let obj = {first:"Paul", last:"Shan"};
  let { first: f, last: l } = obj;
  console.log(f + ' ' + l); // Paul Shan
}

Array destructuring

function func () {
  let arr = ["Paul", "Shan"]
  let [x, y] = arr;
  console.log(x + ' ' + y); // Paul Shan
}

Object literals: property value shorthand

// {x,y} is the same as { x: x, y: y }

function func (argument) {
  let obj = {first:"Paul", last:"Shan"};
  let { first, last } = obj;
  console.log(first + ' ' + last); // Paul Shan
}

Change in object declaration style

let obj = {
  myProp: someValue, // property
  
  myMethod(arg1, arg2) { // method definition
    
  }
};

If you notice, this is not a valid JSON object; but this is the new object declaration style.

Computed property key

Till ES5 you were able to compute the value of a property; but ES6 gives you the power to make a computed key. Below is an example.
  let propKey = 'firstName';
    let obj = {
        [propKey]: "Paul",
        ['last'+'Name']: "Shan",
    };

    console.log(obj.firstName + " " + obj.lastName); // Paul Shan

SHARE THIS ARTICLE

Today everyone knows the importance of a lightning-fast website and how the speed impacts the conversion rate of a business. Today, everyone wants the site to be a PWA so that the mobile users can have an app-like experience with the website because, for the majority of the merchants, the customers come through mobile devices.
Tue Apr 20 2021
Here we are going to see how you can manage backup and restore of Postgres database with docker.
Thu Sep 03 2020
Image sliders or carousels always have increased the UI attraction of websites and they are pretty useful for reflecting the major roles/products too. In case, I am having a website that sells tee-shirts,
Mon Apr 30 2018

About VoidCanvas

This blog was created out of hobby and talks mostly about technology, web development, JavaScript, NodeJS and related topics. Thank you for reading my blog.

Copyright 2022 - www.voidcanvas.com

Popular Articles

Authentication using Google's oAuth api with node.js

Thu Mar 10 2016

OAuth authentications are pretty popular now a days and another thing which is popular is JavaScript. This article shows how to plugin google’s oAuth api for authentication in your own node application.

CSS3 Loader Snippet Collection: (Part 2 - Squares)

Sat Mar 01 2014

This is a continuation of my CSS3 loader snippet collection series. I've provided spinning css3 animation loader in the part 1 of this series and here in part 2, I'm providing various square type loading