Picture of the author
nag5000
  • eval is evil

    Published on
    ·

    Did you know that eval's content see the current context? I mean, const x = 1; return eval('x') will return 1.

    Well, that's not all the magic.

    const x = 1;
    eval('x + 2') // 3
    
    const x = 1;
    window.eval('x + 2') // Uncaught ReferenceError: x is not defined
    
    const x = 1;
    const eval2 = eval;
    eval2('x + 2') // Uncaught ReferenceError: x is not defined
    
    const x = 1;
    (0, eval)('x + 2') // Uncaught ReferenceError: x is not defined
    

    The first one is called "direct eval" and the rest are "indirect evals".

    TIL that Vite (esbuild) warns you about using direct evals. See the reasons here.