Reputation: 543
I'm (re)learning Javascript and it's been recommended to me to avoid mixing ES5 and ES6 type code. But my IDE, Webstorm, keeps warning me that I should be using let and const in my code -- there are tons of yellow flags. Of course I can just turn off those warnings, but should I always use let and const when appropriate, even if the rest of my code is, for the moment, "old school" javascript? (As an aside, I'd welcome any links/advice on/to best practices transitioning to ES6, i.e. the best way to start introducing ES6 into your code). Thanks!
Upvotes: 3
Views: 9265
Reputation: 49
The basic answer to your question: no, it is not ok to use let
and const
in true ES5. You need to use var
. To add to that: if Webstorm is throwing those warnings but you are writing ES5 then your settings are wrong. Go to Settings > Languages & Frameworks > Javascript, and change your Javascript Language Version to ECMAScript 5.1. If you know you're writing ES5 then you should not have it set to be validating your code against the ES6 specification.
Here's some additional info:
Recently I've been working to hook up a transpiler (Babel) to convert all Javascript to ES5 compatible syntax in a production environment. If you want to use ES6 syntax, but still need to support non ES6 compliant browsers (IE9 - IE11 for example) then a transpliler like Babel is necessary. With that in mind I'd like to bring up some specific notes related to let
and const
.
In true ES6 using let
to define a variable creates it within the scope of its block. That means that as soon as the block exits that named variable is discarded. Because of this, something like the following is possible:
const x = 'I am a constant';
if (1 == 1) {
let x = 'Not here for long';
console.log(x); // => 'Not here for long'
}
console.log(x); // => 'I am a constant';
When using let
to create a block scoped instance of x
that takes precedence over const x
inside of this block (our if statement in this case). What Babel turns this into in order to make it compatible with ES5 browsers is actually quite smart:
var x = 'I am a constant';
if (1 == 1) {
var _x = 'Not here for long';
console.log(_x); // => 'Not here for long'
}
console.log(x); // => 'I am a constant';
As you can see here it actually creates a new var with a different name, _x
, so it does not conflict with the original x
.
A final note: If you are using new features like Promise
and Symbol
then a transpiler is not enough. You also need to be using a polyfill for those.
Upvotes: 4