0

If we divide the operation of javascript engine into compilation phase (where that whole lexical scope diagram is setup) Vs running phase (where code is executed using lexical scope setup in compilation phase), when is the scope for function expressions setup? Is it during the compilation or running/interpretation phase?

Also, whenever the scope for the function expression is setup the parent scope will always be the global scope right? (I've seen this happen code, just want to confirm).

noi.m
  • 3,070
  • 5
  • 34
  • 57
  • I think you might be conflating a couple of different things. Here are two good articles that might help: [Javascript Scope and Closures](https://spin.atomicobject.com/2014/10/20/javascript-scope-closures/), and [Of Function Scope and Lexical Scoping](http://pierrespring.com/2010/05/11/function-scope-and-lexical-scoping/). Note especially the part about "Call, Bind, and Apply", – paulsm4 Mar 26 '16 at 20:53

3 Answers3

2

The scope of functions (including function expressions) is set up when the functions are created - which happens in the running phase, not the parsing phase.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • scopes for function expressions are setup in the running phase (which i guess maps to the compile phase in my question)? If possible, could you please forward me a link/article which mentions this. – noi.m Mar 26 '16 at 21:47
  • 2
    Given that JS is an interpreted language with optimising compilers, "phases" don't make too much sense anyway. There's only parsing into an AST, then execution. Which includes setting up functions and compiling their bodies. – Bergi Mar 26 '16 at 22:08
0

It's easier to think of scope as a hierarchy of functions. If you are defining your first function a(), it's parent scope will be the global scope. Each function that is defined with a(), has access to both a()'s scope and the global scope. Every descendant in the tree of function has access to it's parent scope, with the root being the global scope

N R
  • 9
  • 2
0

Actually found few links [1] and [2] had good explanations on this. It seems like (RHS) of the function expressions are interpreted at run time, while function definitions are set on the scope at compile time.

Community
  • 1
  • 1
noi.m
  • 3,070
  • 5
  • 34
  • 57