Modern JavaScript: variable declaration
June 28, 2020In addition to var, a variable can now be declared using let and const keywords.
There are some details to be aware in order to use them properly. Let see some examples.
var
var is function-scoped or globally-scoped. For example:
function testVar() {
var test = "Hello World!";
if (true) {
var test = "Something else";
console.log(test); // expected output: Something else
}
console.log(test); // expected output: Something else
}
testVar();
let
let is block-scoped. For example, we can replace let with var in the previous example. The output, as we can see, is different:
function testLet() {
let test = "Hello World!";
if (true) {
let test = "Something else";
console.log(test); // expected output: Something else
}
console.log(test); // expected output: Hello World!
}
testLet();
const
const works like let, but the value can't be reassigned or redeclared.
const testConst = "Hello";
testConst = "Hello World!"; // expected output: TypeError exception
const does not create immutable objects! Keep this always in mind. Even if we declare an object with const, we are still able to change is content:
const testConstObject = {a: "Hello World!"};
testConstObject.a = "Something else"; // no exception will be throw
To create an immutable object we can use Object.freeze(), but even
in this case JavaScript does not provide a real immutable object: only the first level of the object is immutable, but all the others level can be changed through
reassignement.
