The ES2015's let
and const
keywords give us better (actually useful!) control over variable scope. We can use this to write code in a more terse, cleaner manner.
Mozilla's original implementation of let
had support for non-standard let blocks
that looked like this:
let (x = x+10, y = 12) {
console.log(x+y); // 27
}
Let blocks
also allowed us to define blocks similar to how we used to write with
in the olden days: let (pos = obj.position) { pos.x++; }
. I don't know why this got the boot from the final ES6 spec (I quite like the syntax), but we can recreate the idea using empty blocks and defining the variables like normal:
const stats = new Stats();
{
const dom = stats.domElement;
const style = dom.style;
stats.setMode( 0 );
style.left = "0px";
style.top = "0px";
document.body.appendChild( dom );
}
Thanks to const
and let
behaving sensibly, the dom
and style
are only defined inside the block. This gives us all the power of the let block
, and none of the problems of the old school with
statement.