Showing posts with label Hoisting. Show all posts
Showing posts with label Hoisting. Show all posts

Friday, September 4, 2015

Advanced JavaScript Topics Part 2

We were discussing the let keyword in the Part 1 of this series. We discussed what the advantages and how we can use let keyword in the code. However, let keyword has a problem it does not support hoisting, means if you have declared a variable using let keyword in the mid of the block it would not be available in the part above the declaration of the let keyword.
So you always make sure that let is declared at the top of the block.
As we discussed earlier let keyword kind of Hack the scope implicitly. We can always write the code to make sure when we see we can explicitly identify that this block is a scope. The example given the in the Part 1 of this series used the implicit way. To use the explicit way do it like this

function foo(bar) {
    "use strict"
    let (test = bar) {
        console.log(test) // "bar"  
    }
    console.log(baz) // reference error
}

However, this syntax is rejected by the committee. we can use some other way to make sure we see the block scope in the code as we read the code.

function foo(bar) {
    "use strict"
    /*let */
    {
        let test = bar
        console.log(test) // "bar"  
    }
    console.log(baz) // reference error
}

This is one way to do it. Keyle Simpson have created this great tool to help you with block scoping it is called Let-er .


So, as we started to talk about tools you might want to take a look at traceur-compiler it generates ES 5 code from ES 6 code. As there is development going on in ES 6 you should start writing your code in ES 6 and use a transpiler to convert the ES 6 code to ES 5. You can use grunt-traceur . Other than this you might wanna take a look at the tools for ES 6.


Hoisting


Hoisting is a concept which is developed to understand how JavaScript works when we declare the variables and functions. Take a look at the code below