Reputation: 9682
Looking at the below code, I found a strange and seemingly bad problem with const
:
const path = require('path');
function reWritePath() {
let path = 'blah';
console.log(path);
}
reWritePath();
This seems to go against the point of const
, and I'm surprised to find it can be rewritten in subscopes. Is there a clean way to completely freeze a variable so this can't happen anywhere across the file?
Upvotes: 0
Views: 74
Reputation: 3454
AKX is right - there are really two separate variables named path
. They just happen to have the same name.
Consider this:
const x = 0;
function reWritePath() {
let x = 1;
console.log(x);
}
reWritePath();
console.log(x);
The output of this will be:
1
0
If that's confusing, try renaming one of the variables:
const x = 0;
function reWritePath() {
let y = 1;
console.log(y);
}
reWritePath();
console.log(x);
Upvotes: 0
Reputation: 169051
Those are not the same variables. The same names, yes, but in different scopes.
There is no way of strictly not allowing this to happen -- instead, you should use a linter that can look for name shadowing so you'll at least notice this happening.
Upvotes: 4