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

File upload and Progress events with HTML5 XmlHttpRequest Level 2

The XmlHttpRequest Level 2 specification adds several enhancements to the XmlHttpRequest object. Last week I had blogged about cross-origin-requests and how it is different from Flash\Silverlight's approach .  With Level 2 specification one can upload the file to the server by passing the file object to the send method. In this post I'll try to explore uploading file using XmlHttpRequest 2 in conjunction with the progress events. I'll also provide a description on the new HTML5 tag -  progress which can be updated while the file is being uploaded to the server. And of course, some ColdFusion code that will show how the file is accepted and stored on the server directory.

Server sent events with HTML5 and ColdFusion

There are several ways to interact with the server apart from the traditional request\response and refresh all protocol. They are polling, long polling, Ajax and Websockets ( pusherapp ). Of all these Ajax and Websockets have been very popular. There is another way to interact with the server such that the server can send notifications to the client using Server Sent Events (SSE) . SSE is a part of HTML5 spec:  http://dev.w3.org/html5/eventsource/

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.