Search code examples
javascriptgoogle-chromereferenceerror

ReferenceError on Google Chrome but not on Firefox (Browser Bug?)


This piece of code

eval(`
    let a = 0;
    function f() {}
    function g() { a; }
    console.log(f);
`);

works fine on Firefox 48.0 while causing Uncaught ReferenceError: f is not defined on Google Chrome 52.0.2743.116 (64-bit).

It also works fine on Google Chrome if

  • eval is not used, or
  • the code inside eval is surround with {}, or
  • a is not referenced in g, or
  • let is changed to var, or
  • "use strict" is added before the code

What's happening here?


Solution

  • Looks like it's a novel V8 bug! A more minimal test case is

    eval(`
        var f;
        let a;
        ()=>a
    `);
    f;
    

    Variable-scoped declarations (which includes top-level function declarations) aren't getting properly hoisted out of non-strict eval calls when the call also has a nontrivial lexical declaration.