Explicit Javascript Blocks

I recently learned about explicit block

{
   let foo = 'Hello';
   someFunction(foo);
}

      

I'm still not entirely sure what it does and how we (the developers) can benefit from it.

  • Have you used it before?
  • Do you have any precedent?

Thank you for sharing your experience!

+3


source to share


1 answer


Since let

(both const

and class

and - in strict mode declarations -) are block scoped with ES2015, you can use a separate block for personal information and just fine-tune the scope of the variables for more where we used IIFE.

That is, some ES5 and earlier codes that have a private variable x

:

(function() {
    var x = Math.random();
    console.log(x);
})();
// `x` doesn't exist here

      

x

well contained only in that IIFE.

Now, with ES2015, we can do the same without creating and calling a function:

{
    let x = Math.random();
    console.log(x);
}
// `x` doesn't exist here

      

Likewise, since self-contained blocks allow us to control the scope of variables, we can have more control over the content of the closure. For example, consider the following:

function doSomething() {
    let retainedInformation;
    {
        let something = /*...get some setup information...*/;
        let anotherThing = /*...more setup information...*/;
        let aThirdThing = /*...even more setup information...*/;
        retainedInformation = /*...something figured out using the above...*/;
    }
    return function() {
        // ...use `retainedInformation`...
    };
}

      



Since something

, anotherThing, and

aThirdThing are all out of scope for the function returned by

doSomething , they aren't retained by it, just

savededInformation` is.

But modern JavaScript engines are already optimizing closures all the time, and this whole setup might be best in a function that you call from doSomething

anyway, just as a general principle.


However, we'll probably see a lot of IIFEs because they can return a value. So, for example, if I want a function that uses a private variable, I would probably do:

const foo = function() {
    let privateInfo = 42;
    const foo = () => {
        console.log(privateInfo++);
    };
    return foo;
}();
foo(); // 42
foo(); // 43

      

but not

let foo;
{
    let privateInfo = 42;
    foo = () => {
        console.log(privateInfo++);
    };
}
foo(); // 42
foo(); // 43

      

... although both work.

+5


source







All Articles