How should I declare variables in ES6

Marcus A
Marcus A
Nov 1 · 2 min read

In ES6, the new declaration of variables “let” and “const” has been released.
These declarations are cool because before ES6 we can’t use block-scoped variables. The only declaration we could use was “var” which has function scope but not block scope. This caused a lot of bugs around the world (probably).

// before ES6function getNames() {
for (var i = 1; i <= 10; i++) {
// declare with var
var name = "Marcus" + i;
console.log(name);
}
// this "name" variable still has value
console.log(name); // this code shows "Marcus10"
}

The wonderful ES6 changed this annoying declaration. The declaration “let” and “const” have block scope, which can be accessed in the same block but cannot be accessed from outside of the block.

// after ES6const getNames = () => {
for (let i = 1; i <= 10; i++) {
// const (or let) effects only inside of this block scope
const name = `Marcus${i}`;
console.log(name);
}
// below code gets error because the variable "name" is not declared in this scope
console.log(name);
}

These declarations are very useful because you can avoid getting errors because of global & function scope variables. These declarations can’t be used outside of block so that you don’t have to think about the existence of global scoped & function scoped variables when you are out of this scope if you code like this.


So in my opinion, to avoid getting bugs because of using var, I would like to follow this rule:

  • Use “const” first whenever you want to use variables.
  • Then if you have to change the value of the variable itself, use “let” instead of “const”. (note: the inside of variable declared with “const” can be changed, like inside of Object or Array)
  • Never use var if you use ES6.

(If there is “var” that has been declared already, you can change it but do it carefully and see what will happen when you run the code after change the declaration.)

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade