- A program has state when it can store value in variables and can modify or use it.
- The scope is the set of rules which are used to store variables and finding those variables later to use them.
- Even though JS comes under the category of "dynamic" or "interpreted" languages but it is compiled language because it is compiled few mere microseconds before execution. JITs (Just in Time) is used for performance enhancements.
- There are three major components of JavaScript Compilation process: Engine, Compiler and Scope.
- Engine
- Start to finish compilation
- Execution
- Compiler
- Tokenizing
- AST Generation (Parsing)
- Code Generation
- Scope
- Collect and maintain a lookup of all variables
- Enforces set of rules as to how these are accessible to currently executing code
- How JS processes the statement
var a = 2
?
- Compiler produces code for Engine to execute, Engine consults the Scope again to ask if a variable exists (this time it does because compiler created it). Engine then uses the variable and assigns the number to it.
- Compiler asks scope to see if a variable already exists in a particular scope collection. If yes, proceed else create it.
- LHS lookup means when a lookup is for a variable on the left-hand side of the expression. This includes looking up if the container exists in the first place. If this lookup fails, it creates a variable in the global scope in non-strict mode else it gives ReferenceError.
- RHS lookup means when a lookup is for a variable on the right-hand side of the expression. This includes getting the variable only. If this lookup fails this gives ReferenceError.
- Nested Scope/ Lexical Scope If a variable cannot be found in the immediate scope, Engine consults the next outer containing scope, continuining until is found or until the outermost scope (global) has been reached.