denysdovhan / wtfjs

🤪 A list of funny and tricky JavaScript examples
http://bit.ly/wtfjavascript
Do What The F*ck You Want To Public License
35.06k stars 2.55k forks source link

Direct call and indirect call of `eval` behave differently #327

Open wheatup opened 3 months ago

wheatup commented 3 months ago

When calling eval indirectly, it uses the top scope. This means you can access the top scope variables even in a local scope where the same variable name is redefined. (Note that the variable is defined with let, so it is not a property of the global object.)

let foo = 'outer';

(() => {
  let foo = 'inner';

  console.log(eval('foo'));  // > "inner"
  console.log(eval?.('foo'));  // > "outer"
})();

This behavior is explained in the MDN documentation on eval.

Rudxain commented 1 month ago

Peak black magic