3 ms·
A javascript engine can tell that a variable is used in a const-like way if it statically checks that `eval` is not used in the within the variable's scope. I b
by AgentME 7y ago
A javascript engine can tell that a variable is used in a const-like way if it statically checks that `eval` is not used in the within the variable's scope. I believe there are a few optimizations in V8 and other engines that are disabled if eval is used in the scope at all. (I don't know if there are any optimizations around a variable being used in a const-like way. As you said, const in JS is mainly for developers.)
Given code like `function foo(fn, str) { var foo = 0; fn(str); return foo; }`, you might be wondering what happens if foo is called with `foo(eval, "foo = 1");`. The answer is that a standard eval call isn't actually a normal function call but better understood as a special syntax resembling a function call. There's a big difference between `eval(x);` and `var e = eval; e(x);`. When you take the value of `eval` (by passing it as a parameter or assigning it to a variable, etc), the value you get is actually the "indirect eval" function, which works slightly differently than standard eval: it does not get access to the local scope that it's called in. This means its usage won't break any optimizations that assume the local scope won't be modified.