
Variables declaration
In the previous code sample, we used the familiar var keyword of JavaScript to declare our variable.
Before we code anything else together, you really need to know that var is a keyword that you should forget about and never use again.
Why? The issue is that var does not support block scope. Instead, variables declared with var are function-scoped and any variable declarations in a block will get hoisted to the surrounding function.
Hoisting is a weird JavaScript concept. In JavaScript, variable declarations (and declarations in general) are treated first, before anything else is executed. This means that declaring a variable anywhere is exactly the same as declaring it at the top. This also means that a variable can be used before it is declared, which is counter-intuitive, to say the least.
This might sound unclear, so let us give you an example:
var a = 12;
var result = a + b;
var b = 30;
console.log("Result: ",result);
The previous code is a perfectly valid JavaScript code (but is certainly not recommended).
Up until ES5, var was the only way to declare variables, but this has changed with ES2015, which has introduced two new keywords: let and const. Both of these keywords do support block scope.
The let keyword is the safer alternative to var, while const allows you to define constants.
We are putting constants between quotes because the const keyword does not make objects immutable; it only ensures that the variable cannot be reassigned, but the contents of the object it points to can be modified.
Here is the recommended order of preference: const > let > var.
Why? As you'll see throughout the book, defensive programming has many merits and can help you write better and safer code. While programming defensively, you'll notice that immutability has many benefits, for example, to avoid side effects and surprises.
In practice, even if const does not guarantee immutability, it is still a step in the right direction and it clearly conveys the intent of your code, which is very important. Hence, our recommendation is to use const whenever possible and to only use let when you need to be able to assign different values.