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.
Thanks for sharing your experience!
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, and
aThirdThingare all out of scope for the function returned by
doSomething, they aren't retained by it, just
retainedInformation` 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With