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:
deleteis only effective on an object's properties. It has no effect on variable or function names.
The example provided is similar to yours.
x = 42;         // creates the property x on the global object
var y = 43;     // declares a new variable, y
delete x;       // returns true  (x is a property of the global object and can be deleted)
delete y;       // returns false (delete doesn't affect variable names)
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 eval weirdness:
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:
eval may capture assignments, but not var declarations
eval'd vars hoist normally, so evals may capture assignments similar to with:
function f() { { let x = "inner"; eval("var x = 'outer'"); print(x); // "outer" } }
If I'm reading this correctly, then my earlier assumption was right. eval() does not evaluate var declarations by declaring  a variable. It must create a property or be treated as a property in order for delete to work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With