You can effectively "override" a const
if the subsequent declaration is in a nested function scope.
You can also override a const
in a block with let
, as that will keep the declaration lexically scoped to that block
Example: The JS engine will not allow an override of the const, even though the var
is in a nested block scope
function myScopedConst() {
const myScopedConst = 42;
console.log('myScopedConst:: before the block ->', myScopedConst);
{ var myScopedConst = 'reassigned';
console.log('myScopedConst:: inside the block ->', myScopedConst);
}
console.log('myScopedConst:: after the block ->', myScopedConst);
}
Example: This will not allow an override of the const, because the const
and let
are in the same scope
function myScopedConst() {
const myScopedConst = 42;
console.log('myScopedConst:: before the block ->', myScopedConst);
let myScopedConst = 'reassigned';
console.log('myScopedConst:: inside the block ->', myScopedConst);
console.log('myScopedConst:: after the block ->', myScopedConst);
}
Example: This will allow an override of the const, because the let
is in a nested block scope
function myScopedConst() {
const myScopedConst = 42;
console.log('myScopedConst:: before the block ->', myScopedConst);
{ let myScopedConst = 'reassigned';
console.log('myScopedConst:: inside the block ->', myScopedConst);
}
console.log('myScopedConst:: after the block ->', myScopedConst);
}
Example: This also will allow for an override of the const
function myScopedConst() {
const myScopedConst = 42;
console.log('myScopedConst:: before the block ->', myScopedConst);
(function deepScope() {
var myScopedConst = 'reassigned';
console.log('myScopedConst:: inside the block ->', myScopedConst);
})();
console.log('myScopedConst:: after the block ->', myScopedConst);
}