If I run the following code in google chrome console I get the following results
var x = 1;
alert(delete x); // false
eval('var y = 2');
alert(delete y); // true
Why in the first example the variable is not deleted and in the second example it is deleted?
From the Mozilla JS Docs for
delete:The example provided is similar to yours.
So, why does
alert(delete y);work? I couldn’t nail down the exact answer, but basically you cannot rely on the scope of eval.I think
eval('var y = 2');does not get declared as a variable and is treated as a property, but I haven’t found evidence for that yet other than the results of our tests. I’m going to continue researching to see if I find the exact reason.Other articles on
evalweirdness:EDIT 0
Based on @Xavier Holt’s comment, I looked up hoisting and scope in regards to
eval. This scope cheatsheet from Mozilla Dev docs had the following:If I’m reading this correctly, then my earlier assumption was right.
eval()does not evaluatevardeclarations by declaring a variable. It must create a property or be treated as a property in order fordeleteto work.