JavaScript VM internals
EventLoop, Async and ScopeChains
by Arindam Paul / @geek_paul
Amazon Campus
© Amazon 2015
"When there is freedom from mechanical conditioning, there is simplicity. The classical man is just a bundle of routine, ideas and tradition. If you follow the classical pattern, you are understanding the routine, the tradition, the shadow - you are not understanding yourself." - Bruce Lee
“When you don’t know what you believe, everything becomes an argument. Everything is debatable. But when you stand for something, decisions are obvious.”
― Jason Fried, Rework
Agenda
- JavaScript Interpretation and Memory Model
- Compilation and Lexical Scope
- Function Execution
- Scope Chains
- JavaScript Runtime and Event loop
- Async Examples
- Single Threaded parallel execution
Some Gotchas
Java ≠ JavaScript
Just like
Ham ≠ Hamburger
JavaScript Base Concepts
- JavaScript reads top to bottom and runs to completion.
- Everything is extensible and almost everything in JavaScript is mutable.
- JavaScript is functional language with closures and lamda expressions inherited from Scheme.
- It is also prototypal language with objects inheriting from objects directly (inheriting this nature from Self.)
- Scopes can be created only using functions (functional scope) and all variables defined in a scope are hoisted to the top of the scope.
JavaScript Types
No strong typing
Memory Allocation and Garbage Collection
Let's pretend to be the Runtime and execute the code
Compilation and Execution: Part 1
Compilation and Execution: Part 2
Compilation and Execution: Part 3
Compilation and Execution: Part 4
Closures
What happens when a function is executed outside of it's original scope chains? Moreover, what happens when a variable holds on to a function reference which get's defined in such deep function execution chain.
So What is Closure?
It is an implicit, permanent link between a function and it's scope chain..
A function definition's (lambda) hidden [[scope]] reference.
- Holds the scope chain (preventing garbage collection.)
- It is used and copied as the "outer environment reference" anytime the function is run.
Closure in Action: Contd.
Closure in Action: Contd.
Implicit Closure
var data = "My Data!";
setTimeout(function() {
console.log(data); // prints "My Data!"
}, 3000);
Explicit Closures
function makeAdder(n) {
var inc = n;
var sum = 0;
return function add() {
sum = sum + inc;
return sum;
};
}
var adder3 = makeAdder(3);
Event Loop and Async Programming
Enough Slides, let's go directly to the demo and see it in Action.
And the moment when it all worked...
Questions?
"When your syntax is more beautiful, you can let the reader of your code get past the syntax and closer to the intentions"