Consider using `let` or `const` instead of `var`JS-0239
It is recommended to use let or const over var.
This will help prevent re-declaration of variables that are in the global scope when using var.
ES6 allows programmers to create variables with block scope instead of function scope using the let and const keywords.
Block scope is common in many other programming languages and helps programmers avoid mistakes such as this one:
var count = people.length;
var enoughFood = count > sandwiches.length;
if (enoughFood) {
var count = sandwiches.length; // accidentally overriding the count variable
console.log("We have " + count + " sandwiches for everyone. Plenty for all!");
}
// our count variable is no longer accurate
console.log("We have " + count + " people and " + sandwiches.length + " sandwiches!");
Block scoped variables shadow outer declarations instead of writing to them.
NOTE: There are certain edge cases where users might want to consider var. Consider this example:
var lib = lib || { run: () => {} }
Here, lib might be a library that is exposed to an HTML file using a <script> tag.
The var keyword helps avoid re-writing lib if it has already been declared via an injected script that was executed before this one.
Ideally, you should let bundlers worry about cases like this.
But if you want to use var anyway, consider using a skipcq comment, or disabling the issue altogether.
Bad Practice
var x = "y";
var CONFIG = {};
Recommended
let x = "y";
const CONFIG = {};