Question

Say I have this function:

function A() {
  function B() {
    return 1;
  }

  return 1 + B();
}

Does function B gets compiled every time when I call function A?

I remember someones says it won't. But my memory gets rusty, and I cannot find the reference.

Was it helpful?

Solution

The JavaScript standard states that a JavaScript execution environment must parse the function and produce early errors refusing to execute any code in the script if they exist (such as missing close quotes, unmatched curly braces etc.). It says nothing about what happens after than.

However, all modern engines will produce native code corresponding to the function prior to executing it. All subsequent invocations will use the code generated earlier. There are times where an engine will regenerate the code by using information it collected by execution or it might inline the code of the function if it can determine that would result in better execution time.

OTHER TIPS

JavaScript is an interpreted language, not a compiled one, therefore it never compiles the function.

Edit: Unless your javascript engine optimized by compiling, in which case it depends on which engine it is but don't worry about it because it's not going to recompile it without a reason.

If you mean invoked (or called) as opposed to compiled, the answer is yes. B is invoked everytime A is invoked as A calls B.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top