0

As we know JavaScript engine actually will compile JavaScript code before it interprets it. So, functions (variables as well) are processed first before any part of our code is executed. It's called "hoisting".

I want to understand when js code is loaded js engine will compile functions declarations in global scope only or nested also?

Martin
  • 201
  • 1
  • 4
  • The scope doesn't matter for processing here. – connexo Feb 25 '18 at 09:08
  • @connexo I mean in root part – Martin Feb 25 '18 at 09:10
  • 1
    Parse them? Yes of course. Compile them? No, not necessarily. That might be delayed until the function is actually called - it's a [JIT compiler](https://en.wikipedia.org/wiki/Just-in-time_compilation) and the heuristics when exactly to do what might change at any time. – Bergi Feb 25 '18 at 09:37

1 Answers1

0

To be frank this is JS engine internals, and javascript specification doesn't dictate if functions are also compiled when loading file.

But answering generically, JS engines does not compile the function internals until the function is called, as it is important for JS engines that initial compile / load time is minimal.

In the first pass / compile, all engine is interesting is to find variables, and functions, since, functions create a closure, it is not interested in the things inside function until the function is called.

So to answer your question, engine will normally only compile functions in the current scope, which can be global scope or another function scope, and it does not compile nested functions

Jiby Jose
  • 3,745
  • 4
  • 24
  • 32
  • `[...]JS engines does not parse the function internals until the function is called[...]` thats not true. For nearly all current JS engines, you will get a SyntaxError, for any part of the code, so the engines do a full parsing of the file. But the JIT Compiler most certainly won't compile all code. – t.niese Feb 25 '18 at 09:19
  • 1
    you are right, that was a typo, i was meaning compile and not parse, i updated my answer – Jiby Jose Feb 25 '18 at 09:21