Skip to main content

Learning ES6 - using let, const and Temporal Dead Zone

I've finally started to learn EcmaScript 6 (ES2015) and thought it would be good to start writing about it as I learn. There are a bunch of features in ES6 and a good place to start would be to learn the use of let and const. I haven't deep dived into all the features yet, but I eventually will. This post is about the use of let and const keywords to create variables. I'm a big fan var scope, but I think I'm going to abdicate var scoped variables in favor of let and const.

The primary difference between var and let scoped variables is it's visibility. A var scoped variable is visible throughout the function where as let scoped variable is visible only inside the block in which it is declared. Thinking about block scope now, I realize that many times I write if statements and declare variables as required. With var scope, the variable would be visible throughout the function where as with let scope, the visibility is limited to the block in which it's declared:


A let scoped variable is visible in the block in which it's declared and also in child blocks, unless the same named variable is declared in the child block as well. In this example, the variable 'a' (with value 10) is visible throughout the function but not inside function test. Inside function test, a variable with the same name is let scoped, thus overriding the visibility of variable 'a' at the parent function level. Notice that the let scoped variables are visible only in the block in which they are declared. The variables declared in the inner blocks will cease to exist once the execution crosses the block.

On Temporal Dead Zone (TDZ):

Variables declared with var scope are hoisted and return undefined when one tries to access it before it's definition. In case of let scoped variables, a ReferenceError is thrown. Although, this infers that the let scoped variables are not hoisted but they are indeed hoisted. See the note here: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-let-and-const-declarations.

It mentions that:

"The variables are created when their containing Lexical Environment is instantiated but may not be accessed in any way until the variable’s LexicalBinding is evaluated."

From the above statement, a let scoped variable is instantiated meaning that the variable is hoisted but it's not available until a value is assigned to it. Another example, would be:

let a = b, b = 1;

Again a ReferenceError is thrown mentioning that 'b is not defined'. The Temporal Dead Zone starts when the block containing the let scoped variable is encountered and it ends when the definition of the variable is found. In TDZ, the variables would throw a ReferenceError even if the same variable is present in it's enclosing block i.e. the parent block.

On const:

A const scoped variable is similar to a let scoped variable except that it mandates a value to be assigned to it. Any attempt made to change the value of the variable would result in an error. For example, when you use a const variable in a for loop, an error is thrown when you try to increment the value:

for (const i=0; i < 3; i++) {      console.log(i); }

One of the pitfalls I have observed with const scoped variables is that the value that it is bound to is not a constant:

const a = {x: 1}; a.y = 2; //valid const b = [1, 2, 3]; b.push(4); //valid

I'm not sure whether this is the right thing for constants. Although, one can make it non-writeable by using Object.freeze.

Going forward, I would use const for constant variables and for functions which are var scoped by default. Also, let seems to be a good choice over var for scoping variables.

Comments

Popular posts from this blog

Adding beforeRender and afterRender functions to a Backbone View

I was working on a Backbone application that updated the DOM when a response was received from the server. In a Backbone View, the initialize method would perform some operations and then call the render method to update the view. This worked fine, however there was scenario where in I wanted to perform some tasks before and after rendering the view. This can be considered as firing an event before and after the function had completed its execution. I found a very simple way to do this with Underscore's wrap method.

De-obfuscating javascript code in Chrome Developer Tools

I had blogged about JavaScript debugging with Chrome Developer Tools  some time back, wherein I have explained how these developer tools can help in debugging javascript code. Today Google Chrome 12 was released and my Chrome browser was updated to this version. As with every release, there have been some improvements made on performance, usability etc,. One feature that stood out for me is the ability to De-obfuscate the javascript code. What is Minification? Minification is the process of removing unnecessary characters such as white spaces, comments, new lines from the source code. These otherwise would be added to make the code more readable. Minifying the source code helps in reducing the file size and thereby reducing the time taken to download the file. This is the reason why most of the popular javascript libraries such as jQuery are minified. A minified jQuery file is of 31 KB in size where as an uncompressed one is about 229 KB. Unfortunately, debugging minified javascript f

On GraphQL and building an application using React Apollo

When I visualize building an application, I would think of using React and Redux on the front-end which talks to a set of RESTful services built with Node and Hapi (or Express). However, over a period of time, I've realized that this approach does not scale well when you add new features to the front-end. For example, consider a page that displays user information along with courses that a user has enrolled in. At a later point, you decide to add a section that displays popular book titles that one can view and purchase. If every entity is considered as a microservice then to get data from three different microservices would require three http  requests to be sent by the front-end app. The performance of the app would degrade with the increase in the number of http requests. I read about GraphQL and knew that it is an ideal way of building an app and I need not look forward to anything else. The GraphQL layer can be viewed as a facade which sits on top of your RESTful services o