It is less of a problem now but I'd argue there's still a reason for that general idea.
Theoretically, it is possible for, say, some third-party library to write code like this following:
let count = 0;
function getCount() {
return count++;
}
Now, if you tried to create your own count
variable in the same scope, you'd get an error:
// 3rd-party
let count = 0;
function getCount() {
return count++;
}
// Your code
let count = 1;
However, you can make the code cleaner by using actual blocks instead of IIFEs.
// Still bad 3rd party
let count = 0;
function getCount() {
return count++;
}
// Your code
{
let count = 10;
console.log(count);
console.log(getCount());
console.log(count);
console.log(getCount());
}
In the future, you should be able to encapsulate your code in modules which will have their own scope and you won't need to wrap your code in an IIFE or a block.
let
keyword are not attached towindow
object" - but they are still global. So if you are writing scripts, you will need to put them in a block or an IIFE. – Saberhagen