Why Declared Variables In Javascript Are Non-configurable In The Current Scope?
Solution 1:
Because otherwise every x
might or might not throw an error or might suddenly refer to another variable:
let x = 2;
{
let x = 3;
if(Math.random() > 0.5) delete x;
console.log(x); // ?!
}
That makes code conpletely error prone and unpredictable and makes it impossible to optimize, every line might suddenly become a syntax error, and thats why it is not possible to delete variables that way.
However there is another way to get this behaviour by adding an object as scope which you can mutate, and thats the reason why no one uses the with
statement:
const scope = { b: 2 };
with(scope) {
console.log(b); // 2delete scope.b;
console.log(b); // reference error
}
Solution 2:
You cannot delete a variable if you declared it (with var x;) at the time of first use. However, if your variable x first appeared in the script without a declaration,
you can delete the variable if you didn't use var keyword.
you can get more information from this resource http://www.javascripter.net/faq/deleteavariable.htm
Post a Comment for "Why Declared Variables In Javascript Are Non-configurable In The Current Scope?"