ES6 variable declaration – let and const


In standard Javascript, the only way to declare a variable in JavaScript was to use the keyword var.

But, in ES6 there are now two new ways to declare variables in JavaScript: let and constlet and const have some other interesting properties.

  • Variables declared with let can be reassigned, but can’t be redeclared in the same scope.
  • Variables declared with const must be assigned an initial value, but can’t be redeclared in the same scope, and can’t be reassigned.

Below is the example to show how let and const is being used:

const CHARACTER_LIMIT = 255;
const posts = [
"Mallik",
"talksjava ",
".com"
];

// prints posts to the console
function displayPosts() {
for (let i = 0; i < posts.length; i++) {
console.log(posts[i].slice(0, CHARACTER_LIMIT));
}
}

displayPosts();

Output:

Mallik

talksjava

.com

The big question is when should you use let and const? The general rule of thumb is as follows:

  • use let when you plan to reassign new values to a variable, and
  • use const when you don’t plan on reassigning new values to a variable.

Since const is the strictest way to declare a variable,  you always declare variables with const because it’ll make your code easier to reason about since you know the identifiers won’t change throughout the lifetime of your program. If you find that you need to update a variable or change it, then go back and switch it from const to let.