You Don't Know JS

Notes from Scope & Closures by Kyle Simpson(O'Reilly) |  © 2014 Kyle Simpson 978-1-449-33558-8

      In Progress

What is Scope?

Chapter 1

Compiler Theory

In Traditional compiled-language process, code/program will undergo the following steps before it executed.

1. Tokenizing/Lexing

       Breaking up a string of characters into meaningful chunks

 

2. Parsing

       Taking a stream of tokens & turning into a tree of nested elements; which collectively represent the grammatical structure of the program. This tree is called as "AST - Abstract Syntax Tree"

 

3. Code-Generation 

       Process of taking an AST & turning it into executable code.


    var a = 2;

Understanding Scope

Engine

Compiler

Scope

The Cast

Responsible for start-to-finish compilation & execution of program

One of engine's friends; handles all the dirty work of parsing & code-generation

Another friend of Engine;  Collects & maintains a look-up list of all the declared identifiers(var); enforces strict set of rules as to how these are accessible

Back & Forth

Lets breakdown how Engine & Friends will approach the program,


    var a = 2;

A reasonable assumption could be summed by this pseudo code:

1. ALLOCATE MEMORY FOR A VARIABLE, LABEL IT a
2. ASSIGN THE VALUE 2 INTO THE VARIABLE

Unfortunately that's not quite accurate. Compiler will instead process as:

1. Encountering var a, Compiler asks Scope to see if a variable a already exists for that particular scope collection. If so, compiler ignores this declaration and moves on. Otherwise Compiler asks Scope to declare a new variable a  for that scope.

2. Compiler then produces code for Engine to later execute, to handle the a = 2  assignment. The code Engine runs will first ask Scope if there is a variable called a accessible in the current scope collection. If so, Engine uses that variable. If not, Engine looks elsewhere (Nested Scope).

Back & Forth: Summarize


    var a = 2;

To Summarize: 2 Distinct actions are taken for a Variable Assignment

1. Compiler declares a variable(if not previously declared) in the current scope

2. When executing, Engine looks up the variable in Scope & assigns to it, if found

Made with Slides.com