Search code examples
javascriptv8

Does Javascript engine see constant variables in advance?


Consider this chunk of code

function getPow() {
    const a = 2
    return Math.pow(2, a)
}

If a is a constant and it's not used by anything but the pow function, will the javascript engine evaluate the math equasion in advance (creational phase) and put the results in return or the function will do the computation every time it's invoked?

And is it the same for all engines (V8, SpiderMonkey, etc...)?


Solution

  • Yes, V8's optimizing compiler supports "constant folding" (i.e. performing calculations at compile time when their inputs are known at compile time), and this optimization does trigger for the example in the question.

    It doesn't matter whether const a is used for anything else or not.

    While it's probably true that all engines do this, it's also an internal implementation detail, and I wouldn't recommend to rely on it (in any engine). It also shouldn't really matter, in most cases.