Scopes & Reassigning
Const and Let inside of scopes and reassigning them
Constant scope
The constant variable is defined outside the if-statement but can still be accessed inside of it.
const variable = 'test';
if (true) {
console.log(variable);
} $ node .
"test"Reassign in different scope
In here, variable is defined at the top of your code, and is reassigned a different value inside an if-statement, the new value is still accessable outside (and bellow) the if-statement.
Truely if-statement
let variable = 'test';
if (true) {
variable = 'maybe';
}
console.log(variable);Falsely if-statement
Constant in wrong scope
The constant variable is defined in a lower scope than the console.log and is therefor not accessable and will throw a run time error.
Reassigning
Giving a variable a new value is not possible with const, only with let. Even if this sounds like an advantage for the let-keyword, you shouldn't use it if you don't need to as it uses more ram.
Last updated
Was this helpful?