
JavaScript first appeared 22 years ago in 1995, in most of its lifetime there has been only one way to declare a variable using the var keyword. Some declarations of var can have some unexpected behaviours due to scope. That’s why with the sixth version of JavaScript ECMAScript 2015 developers decided to introduce two new keywords ‘Const’ & ‘Let. In this article, we will run through each and help decide what you should be using in your JavaScript.
Const
‘Const’ is often the best option for declaring variables. ‘Const’ is an abbreviation for constant meaning the variable shouldn’t change.
For example.
const pi = 3.14159;
The ‘const’ declaration stops the variable being overwritten by any stray variables. Meaning you can’t assign pi to another value. We can test this out by using the console window in chrome. Open up the Const Sample by clicking the link above. With the console window type in our constant pi. This will give use our value 3.14159. If we try to change the value of pi we get an error.
You should only use a ‘const’ for declaring variables that shouldn’t change. If you expect the value to change each time a script runs eg a score or age, you should use the keyword ‘Let’.
Let
‘Let’ is often the best option for declaring variable were the value is likely to change similar to how var works. The difference being ‘Let’ variables are block-scoped so helps defend against those var scoped errors. We have a basic ‘Let’ example below.
let score = 0;

const person = {
first_name: "Gary",
job: "Developer"
}
function personDescription(person) {
let description = person.first_name;
if (person.job) {
description = description + " is a ";
description = description + person.job;
}
console.log(description);
}
personDescription(person);


The console will throw up an error. This happens because we’re are trying to re-assign in the description in the if block. We could change it to ‘var’ and the script would work but unlike var, it has block level scoping which comes in handy in for loops. For example, using a counter in a for loop can have some unexpected results. Let’s look at another code snippet.
const buttons = document.getElementsByTagName("button");
for (var i = 0; i < buttons.length; i++) {
const button = buttons[i];
button.addEventListener("click", function () {
alert("Button " + i + " Pressed");
});
}