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

How to use the APP_INITIALIZER token to hook into the Angular bootstrap process

I've been building applications using Angular as a framework of choice for more than a year and this post is not about another React vs Angular or the quirks of each framework. Honestly, I like Angular and every day I discover something new which makes development easier and makes me look like a guy who built something very complex in a matter of hours which would've taken a long time to put the correct architecture in place if I had chosen a different framework. The first thing that I learned in Angular is the use of the APP_INITIALIZER token.

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...

Using MobX to manage application state in a React application

I have been writing applications using React and Redux for quite some time now and thought of trying other state management solutions out there. It's not that I have faced any issues with Redux; however, I wanted to explore other approaches to state management. I recently came across MobX  and thought of giving it a try. The library uses the premise of  `Observables` to tie the application state with the view layer (React). It's also an implementation of the Flux pattern wherein it uses multiple stores to save the application state; each store referring to a particular entity. Redux, on the other hand, uses a single store with top-level state variables referring to various entities.