Ecmascript Features 4: Let and use strict
Sorry there wasn't a post in this series last week - I wasn't feeling so good. I am better now though.
This week's ES6 post will cover the let keyword. Normally in Javascript variables are declared with var and are function level. This means that once you declare a variable in a function (even if it is inside a nested block like a loop, it is available until that function's scope is removed from memory (note that a function's scope can stick around even after it completes in certain asynchronous cases).
The let keyword offers more control over the lifetime of your variables by reducing the scope of variables declared to block level. This means that once a block is removed from memory (again, this is usually when it completes - but there are certain asynchronous exceptions) the variable is destroyed.
For example, the following would work:
var foo = true;
if(foo) {
var bar = "oranges";
}
console.log(bar);
But this wouldn't work:
var foo = true;
if(foo) {
let bar = "oranges";
}
console.log(bar);
As of the time of writing, there are actually 2 problems with the second example. The first problem, as you have probably guessed, is that the let keyword is used inside the if block to declare a variable called bar, but the new variable is referenced outside of the if block's scope - causing a problem.
The second problem is to do with the second half of the title of this post. At the current time the above will also cause the following error in chrome based consoles:
Uncaught SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
What is going on here? What is strict mode?
Strict mode has actually been floating around the internet for a while now (you might have heard of it) and it prevents you from doing the following by throwing an error (normally these just silently fail):
- accidentally creating new global variables by mistyping a variable name
- changing the type of something once created
- assigning to a getter only property
- adding to a fixed object
- deleting undeletable properties
- duplicating argument names in function definitions
- using the
withkeyword - puts
eval()ed code into it's own sandbox - deleting variables
- and a whole bunch of other stuff
It's a long list, right?! Either way, turning on strict mode will help you to both catch bugs quicker and write better code to begin with. To turn it on, just put the following at the beginning of your script or function:
"use strict";
Since this is only a string, it makes it backwards compatible with older browsers, too!
That concludes this post. Next time, I will probably be taking a look at the rest and spread operators.
Reddit