Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript explicit blocks

I've learned recently about explicit block

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

I am still not quite sure what it does and how we (developers) can benefit from it.

  • Did you used before?
  • Do you have a use-case?

Thanks for sharing your experience!

like image 364
TheBilTheory Avatar asked Sep 05 '25 03:09

TheBilTheory


1 Answers

Since let (and const and class and — in strict mode — function declarations) have block scope as of ES2015, you can use a standalone block for private information and just generally for more finely-controlling the scope of variables, where we used to use IIFEs.

That is, here's some ES5 and earlier code that has a private variable, x:

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

x is nicely contained to just that IIFE.

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

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

Similarly, since standalone blocks let us control variable scope, we can more explicitly control the content of a closure. For instance, consider this:

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, andaThirdThingare all out of scope for the function returned bydoSomething, they aren't retained by it, justretainedInformation` is.

But modern JavaScript engines already do closure optimization anyway, and all that setup might well be best off in a function you call from doSomething anyway, just on general principle.


That said, we'll still probably see lots of IIFEs, because they can return a value. So for instance, if I want a function that uses a private variable, I'll probably do:

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

rather than

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

...although both work.

like image 115
T.J. Crowder Avatar answered Sep 07 '25 21:09

T.J. Crowder