Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

about eval statement constructs and delete

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?

like image 214
Lorraine Bernard Avatar asked Nov 04 '22 08:11

Lorraine Bernard


1 Answers

From the Mozilla JS Docs for delete:

delete is 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:

  • http://wingolog.org/archives/2012/01/12/javascript-eval-considered-crazy
  • http://brownplt.github.com/2012/10/21/js-eval.html
  • http://blog.rakeshpai.me/2008/10/understanding-eval-scope-spoiler-its.html

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.

like image 58
JSuar Avatar answered Nov 11 '22 07:11

JSuar