SlideShare a Scribd company logo
1 of 21
Download to read offline
Javascript VM Internals
Programming is like a chess, You can learn the rules
in an hour but it takes years to master.
Agenda
● VM Internals
○ Compile & Run Time
○ Run & Load Situations
○ Hoisting
○ Variable Shadowing
○ Scope Resolution
○ Closure
○ Call Stack
○ Render Queue
○ Callback & Callback Queue
○ Event Loop
Some Examples
var employeeId = 'abc123';
function foo() {
employeeId = '123bcd';
return;
}
foo();
console.log(employeeId);
Some Examples
var employeeId = 'abc123';
function foo() {
employeeId = '123bcd';
return;
function employeeId() { }
}
foo();
console.log(employeeId);
Interpreter
An interpreter is a program that reads in as input a source program, along with
data for the program, and translates the source program instruction by
instruction.
Compile & Run
JavaScript is interpreted at runtime by the client browser. There is a tool called
the Rhino JavaScript Compiler that supposedly compiles JavaScript into Java
class files, though.
Hoisting
Hoisting teaches that variable and function declarations are physically moved
to the top of your coding, but this is not what happens at all. What does
happen is that variable and function declarations are put into memory during
the compile phase, but stays exactly where you typed it in your coding.
Closure
A closure is the combination of a function and the lexical environment within which that
function was declared.
It is a permanent link between a function and its scope chain.
Two types of closure:
1. Implicit
2. Explicit
Concurrency Model and Event Loop
Call Stack
A call stack is a mechanism for an interpreter to keep track of its place in a script
that calls multiple functions — what function is currently being run, what functions
are called from within that function and should be called next, etc.
● Javascript runtimes only of heap and call stack.
● One thing at a time === One thread === One call stack.
Call Stack
● When a script calls a function, the interpreter adds it to the call stack and then
starts carrying out the function.
● Any functions that are called by that function are added to the call stack
further up, and run where their calls are reached.
● When the main function is finished, the interpreter takes it off the stack and
resumes execution it left off in the main code listing.
● If the stack takes up more space than it had assigned to it, it results in a
"stack overflow" error.
Heap
Objects are allocated in a heap which is just a name to denote a large mostly
unstructured region of memory.
Event Loop
The Event Loop is a queue of callback functions. When an async function
executes, the callback function is pushed into the queue. The JavaScript engine
doesn't start processing the event loop until the code after an async function has
executed.
Event Loop - Queue
JavaScript runtime contains a message queue, which is a list of messages to be
processed. A function is associated with each message. When the stack has
enough capacity, a message is taken out of the queue and processed. The
processing consists of calling the associated function (and thus creating an initial
stack frame). The message processing ends when the stack becomes empty
again.
Event Loop- Adding Messages
Adding messages In web browsers, messages are added any time an event
occurs and there is an event listener attached to it. If there is no listener, the
event is lost. So a click on an element with a click event handler will add a
message--likewise with any other event.
Event Loop - Run to Completion
Each message is processed completely before any other message is processed.
A downside of this model is that if a message takes too long to complete, the web
application is unable to process user interactions like click or scroll. The browser
mitigates this with the "a script is taking too long to run" dialog.
This differs from C, for instance, where if a function runs in a thread, it can be
stopped at any point to run some other code in another thread.
Event Loop - Zero Delay
Zero delay doesn't actually mean the callback will fire-off after zero milliseconds.
Calling setTimeout with a delay of 0 (zero) milliseconds doesn't execute the
callback function after the given interval.
The execution depends on the number of awaiting tasks in the queue.
Never Blocking
A very interesting property of the event loop model is that JavaScript, unlike a lot
of other languages, never blocks. Handling I/O is typically performed via
events and callbacks, so when the application is waiting for an XHR request to
return, it can still process other things like user input.
Asynchronous Programming
JavaScript is single-threaded. As a result, JavaScript programs must use
async APIs to stay responsive to user input while performing long-running
tasks like server requests and animations. You can't get very far in a JavaScript
program without running across an asynchronous API.
Promises ??
Promises are an alternative to callbacks for delivering the results of an
asynchronous computation. They require more effort from implementers of
asynchronous functions, but provide several benefits for users of those
functions.
Thanks
I am leaving all this to open discussion. Thanks.
Reference:
- Work of Philip Roberts - Euro Conf
- Has Geek talk, Described in You do not know JS - Kyle Simpson
- Concurrency Model - MDN
Next talk, We’ll discuss about Promises and Generators.

More Related Content

What's hot

End to end testing a web application with Clojure
End to end testing a web application with ClojureEnd to end testing a web application with Clojure
End to end testing a web application with ClojureGerard Klijs
 
.Net Architecture and Performance Tuning
.Net Architecture and Performance Tuning.Net Architecture and Performance Tuning
.Net Architecture and Performance TuningGauranG Bajpai
 
Rust kafka-5-2019-unskip
Rust kafka-5-2019-unskipRust kafka-5-2019-unskip
Rust kafka-5-2019-unskipGerard Klijs
 
Ruby vs Node ShiningRay Shanghai
Ruby vs Node ShiningRay ShanghaiRuby vs Node ShiningRay Shanghai
Ruby vs Node ShiningRay ShanghaiJackson Tian
 
Rust with-kafka-07-02-2019
Rust with-kafka-07-02-2019Rust with-kafka-07-02-2019
Rust with-kafka-07-02-2019Gerard Klijs
 
Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular Jalpesh Vadgama
 
Async in .NET
Async in .NETAsync in .NET
Async in .NETRTigger
 
Reactive programming using rx java & akka actors - pdx-scala - june 2014
Reactive programming   using rx java & akka actors - pdx-scala - june 2014Reactive programming   using rx java & akka actors - pdx-scala - june 2014
Reactive programming using rx java & akka actors - pdx-scala - june 2014Thomas Lockney
 
Using Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarUsing Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarXamarin
 
CTU June 2011 - C# 5.0 - ASYNC & Await
CTU June 2011 - C# 5.0 - ASYNC & AwaitCTU June 2011 - C# 5.0 - ASYNC & Await
CTU June 2011 - C# 5.0 - ASYNC & AwaitSpiffy
 
End to-end async and await
End to-end async and awaitEnd to-end async and await
End to-end async and awaitvfabro
 
Async Await for Mobile Apps
Async Await for Mobile AppsAsync Await for Mobile Apps
Async Await for Mobile AppsCraig Dunn
 
PyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous ProgrammingPyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous ProgrammingJuti Noppornpitak
 
Concurrent Ruby Application Servers
Concurrent Ruby Application ServersConcurrent Ruby Application Servers
Concurrent Ruby Application ServersLin Jen-Shin
 
Async and Await on the Server
Async and Await on the ServerAsync and Await on the Server
Async and Await on the ServerDoug Jones
 
Reactive Extensions for JavaScript
Reactive Extensions for JavaScriptReactive Extensions for JavaScript
Reactive Extensions for JavaScriptJim Wooley
 
Java concurrency
Java concurrencyJava concurrency
Java concurrencyfbenault
 

What's hot (20)

End to end testing a web application with Clojure
End to end testing a web application with ClojureEnd to end testing a web application with Clojure
End to end testing a web application with Clojure
 
.Net Architecture and Performance Tuning
.Net Architecture and Performance Tuning.Net Architecture and Performance Tuning
.Net Architecture and Performance Tuning
 
Concurrency in ruby
Concurrency in rubyConcurrency in ruby
Concurrency in ruby
 
Rust kafka-5-2019-unskip
Rust kafka-5-2019-unskipRust kafka-5-2019-unskip
Rust kafka-5-2019-unskip
 
Ruby vs Node ShiningRay Shanghai
Ruby vs Node ShiningRay ShanghaiRuby vs Node ShiningRay Shanghai
Ruby vs Node ShiningRay Shanghai
 
Rust with-kafka-07-02-2019
Rust with-kafka-07-02-2019Rust with-kafka-07-02-2019
Rust with-kafka-07-02-2019
 
Event Machine
Event MachineEvent Machine
Event Machine
 
Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular
 
Async in .NET
Async in .NETAsync in .NET
Async in .NET
 
Grape golilath
Grape golilathGrape golilath
Grape golilath
 
Reactive programming using rx java & akka actors - pdx-scala - june 2014
Reactive programming   using rx java & akka actors - pdx-scala - june 2014Reactive programming   using rx java & akka actors - pdx-scala - june 2014
Reactive programming using rx java & akka actors - pdx-scala - june 2014
 
Using Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarUsing Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek Safar
 
CTU June 2011 - C# 5.0 - ASYNC & Await
CTU June 2011 - C# 5.0 - ASYNC & AwaitCTU June 2011 - C# 5.0 - ASYNC & Await
CTU June 2011 - C# 5.0 - ASYNC & Await
 
End to-end async and await
End to-end async and awaitEnd to-end async and await
End to-end async and await
 
Async Await for Mobile Apps
Async Await for Mobile AppsAsync Await for Mobile Apps
Async Await for Mobile Apps
 
PyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous ProgrammingPyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous Programming
 
Concurrent Ruby Application Servers
Concurrent Ruby Application ServersConcurrent Ruby Application Servers
Concurrent Ruby Application Servers
 
Async and Await on the Server
Async and Await on the ServerAsync and Await on the Server
Async and Await on the Server
 
Reactive Extensions for JavaScript
Reactive Extensions for JavaScriptReactive Extensions for JavaScript
Reactive Extensions for JavaScript
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 

Similar to Javascript VM Internals, Event Loop, Call Stack explained

JavaScript Engines and Event Loop
JavaScript Engines and Event Loop JavaScript Engines and Event Loop
JavaScript Engines and Event Loop Tapan B.K.
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.jsSu Zin Kyaw
 
"Node.js vs workers — A comparison of two JavaScript runtimes", James M Snell
"Node.js vs workers — A comparison of two JavaScript runtimes", James M Snell"Node.js vs workers — A comparison of two JavaScript runtimes", James M Snell
"Node.js vs workers — A comparison of two JavaScript runtimes", James M SnellFwdays
 
JavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptxJavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptxRAHITNATH
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScriptAmitai Barnea
 
Basic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsBasic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsGary Yeh
 
"Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native ""Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native "FDConf
 
Node.js: CAMTA Presentation
Node.js: CAMTA PresentationNode.js: CAMTA Presentation
Node.js: CAMTA PresentationRob Tweed
 
Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3
Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3
Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3Elixir Club
 
Introduction to WAMP, a protocol enabling PUB/SUB and RPC over Websocket
Introduction to WAMP, a protocol enabling PUB/SUB and RPC over WebsocketIntroduction to WAMP, a protocol enabling PUB/SUB and RPC over Websocket
Introduction to WAMP, a protocol enabling PUB/SUB and RPC over Websocketsametmax
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipseanshunjain
 

Similar to Javascript VM Internals, Event Loop, Call Stack explained (20)

JS Event Loop
JS Event LoopJS Event Loop
JS Event Loop
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
 
JavaScript Engines and Event Loop
JavaScript Engines and Event Loop JavaScript Engines and Event Loop
JavaScript Engines and Event Loop
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
 
Asynchronyin net
Asynchronyin netAsynchronyin net
Asynchronyin net
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
"Node.js vs workers — A comparison of two JavaScript runtimes", James M Snell
"Node.js vs workers — A comparison of two JavaScript runtimes", James M Snell"Node.js vs workers — A comparison of two JavaScript runtimes", James M Snell
"Node.js vs workers — A comparison of two JavaScript runtimes", James M Snell
 
JavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptxJavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptx
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScript
 
Training – Going Async
Training – Going AsyncTraining – Going Async
Training – Going Async
 
Basic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsBasic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.js
 
Mobile Application Development class 008
Mobile Application Development class 008Mobile Application Development class 008
Mobile Application Development class 008
 
"Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native ""Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native "
 
Node.js: CAMTA Presentation
Node.js: CAMTA PresentationNode.js: CAMTA Presentation
Node.js: CAMTA Presentation
 
Wwf
WwfWwf
Wwf
 
Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3
Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3
Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3
 
Introduction to WAMP, a protocol enabling PUB/SUB and RPC over Websocket
Introduction to WAMP, a protocol enabling PUB/SUB and RPC over WebsocketIntroduction to WAMP, a protocol enabling PUB/SUB and RPC over Websocket
Introduction to WAMP, a protocol enabling PUB/SUB and RPC over Websocket
 
Windows Workflow Foundation
Windows Workflow FoundationWindows Workflow Foundation
Windows Workflow Foundation
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipse
 

Recently uploaded

TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 

Recently uploaded (20)

TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 

Javascript VM Internals, Event Loop, Call Stack explained

  • 1. Javascript VM Internals Programming is like a chess, You can learn the rules in an hour but it takes years to master.
  • 2. Agenda ● VM Internals ○ Compile & Run Time ○ Run & Load Situations ○ Hoisting ○ Variable Shadowing ○ Scope Resolution ○ Closure ○ Call Stack ○ Render Queue ○ Callback & Callback Queue ○ Event Loop
  • 3. Some Examples var employeeId = 'abc123'; function foo() { employeeId = '123bcd'; return; } foo(); console.log(employeeId);
  • 4. Some Examples var employeeId = 'abc123'; function foo() { employeeId = '123bcd'; return; function employeeId() { } } foo(); console.log(employeeId);
  • 5. Interpreter An interpreter is a program that reads in as input a source program, along with data for the program, and translates the source program instruction by instruction.
  • 6. Compile & Run JavaScript is interpreted at runtime by the client browser. There is a tool called the Rhino JavaScript Compiler that supposedly compiles JavaScript into Java class files, though.
  • 7. Hoisting Hoisting teaches that variable and function declarations are physically moved to the top of your coding, but this is not what happens at all. What does happen is that variable and function declarations are put into memory during the compile phase, but stays exactly where you typed it in your coding.
  • 8. Closure A closure is the combination of a function and the lexical environment within which that function was declared. It is a permanent link between a function and its scope chain. Two types of closure: 1. Implicit 2. Explicit
  • 10. Call Stack A call stack is a mechanism for an interpreter to keep track of its place in a script that calls multiple functions — what function is currently being run, what functions are called from within that function and should be called next, etc. ● Javascript runtimes only of heap and call stack. ● One thing at a time === One thread === One call stack.
  • 11. Call Stack ● When a script calls a function, the interpreter adds it to the call stack and then starts carrying out the function. ● Any functions that are called by that function are added to the call stack further up, and run where their calls are reached. ● When the main function is finished, the interpreter takes it off the stack and resumes execution it left off in the main code listing. ● If the stack takes up more space than it had assigned to it, it results in a "stack overflow" error.
  • 12. Heap Objects are allocated in a heap which is just a name to denote a large mostly unstructured region of memory.
  • 13. Event Loop The Event Loop is a queue of callback functions. When an async function executes, the callback function is pushed into the queue. The JavaScript engine doesn't start processing the event loop until the code after an async function has executed.
  • 14. Event Loop - Queue JavaScript runtime contains a message queue, which is a list of messages to be processed. A function is associated with each message. When the stack has enough capacity, a message is taken out of the queue and processed. The processing consists of calling the associated function (and thus creating an initial stack frame). The message processing ends when the stack becomes empty again.
  • 15. Event Loop- Adding Messages Adding messages In web browsers, messages are added any time an event occurs and there is an event listener attached to it. If there is no listener, the event is lost. So a click on an element with a click event handler will add a message--likewise with any other event.
  • 16. Event Loop - Run to Completion Each message is processed completely before any other message is processed. A downside of this model is that if a message takes too long to complete, the web application is unable to process user interactions like click or scroll. The browser mitigates this with the "a script is taking too long to run" dialog. This differs from C, for instance, where if a function runs in a thread, it can be stopped at any point to run some other code in another thread.
  • 17. Event Loop - Zero Delay Zero delay doesn't actually mean the callback will fire-off after zero milliseconds. Calling setTimeout with a delay of 0 (zero) milliseconds doesn't execute the callback function after the given interval. The execution depends on the number of awaiting tasks in the queue.
  • 18. Never Blocking A very interesting property of the event loop model is that JavaScript, unlike a lot of other languages, never blocks. Handling I/O is typically performed via events and callbacks, so when the application is waiting for an XHR request to return, it can still process other things like user input.
  • 19. Asynchronous Programming JavaScript is single-threaded. As a result, JavaScript programs must use async APIs to stay responsive to user input while performing long-running tasks like server requests and animations. You can't get very far in a JavaScript program without running across an asynchronous API.
  • 20. Promises ?? Promises are an alternative to callbacks for delivering the results of an asynchronous computation. They require more effort from implementers of asynchronous functions, but provide several benefits for users of those functions.
  • 21. Thanks I am leaving all this to open discussion. Thanks. Reference: - Work of Philip Roberts - Euro Conf - Has Geek talk, Described in You do not know JS - Kyle Simpson - Concurrency Model - MDN Next talk, We’ll discuss about Promises and Generators.