SlideShare une entreprise Scribd logo
1  sur  28
JS behind the scene
(JavaScript Engines and Event loops )
Tapan B.K.
Software Engineer
Insight workshop
btapaniw@gmail.com
bktapan16@gmail.com
+977-9849-716-660
1. Execution Context
2. Execution Stack
3. Variable Object
4. Scoping and the Scope Chain
5. The ‘this’ Keyword
6. Hoisting (function and variable)
JS Behind the Scene also contains:
Expected Output:
But actual Output is
What is JavaScript?
1. High level
2. Single threaded
3. Garbage collected
4. Interpreted or just-in-time compiled
5. Prototype-based
6. Multi-paradigm
7. Dynamic weakly typed language
8. With a non-blocking event loop
What happens to our JS code?
Summary:
Our code -> parser -> no errors then parser produces abstract syntax tree ->
converts it to machine code -> done conversion -> code runs
Some Popular Javascript Engines
V8: Used in Chrome and chromium-based browsers (Google)
SpiderMonkey: Used in firefox (Mozilla)
JavaScriptCore/Nitro : Used in safari browser (Apple)
Chakra: Microsoft Edge and Internet Explorer (Microsoft)
JerryScript: lightweight engine for Internet of things
JavaScript Runtime Overview
Call Stack
Correction Note: Actual Output is 100
Call Stack Explained
1. The call stack is a LIFO queue (Last In, First Out).
2. Stacks holds our function calls. On each new
function call, it’s pushed on top of the stack
3. The event loop continuously checks the call stack
to see if there’s any function that needs to run.
4. While doing so, it adds any function call it finds to
the call stack and executes each one in order.
Error Stack
Max Call Stack(Stack Overflow)
Web API
Some of the web APIs are:
1. Console API
2. Web storage API
3. DOM API
4. Drag and Drop API
Full Lists of Web API
Provides extra super Power to Developer
The
Event
Table &
Event
Queue
Call back Queue / Event Queue
The event loop facilitates this process; it constantly checks whether or not the
call stack is empty. If it is empty, new functions are added from the event
queue. If it is not, then the current function call is processed
Event loops
1. The event loop is the secret behind JavaScript
asynchronous programming.
2. JS executes all operations on a single thread, but using
a few smart data structures, it gives us the illusion of
multi-threading.
3. Event loops are not Javascript specific as they are
handle by Browser. They do just in time compilation.
Event Loop
The event loop got its name because of how it's usually
implemented, which usually resembles:
queue.waitForMessage() waits synchronously for a message to arrive
(if one is not already available and waiting to be handled).
Event loops with the promises
Output:
Types of of asynchronous tasks:
The macro tasks:
1. They are programmed so that the browser can
ensure that they are executed sequentially
when accessing from your internal engine to
Javascript.
2. For example, callbacks of browser events (an
onClick) or those of functions such as
setTimeout
Types of of asynchronous tasks:
The microtasks:
A microtask is a short function which is executed after the
function or program which created it exits and only if the
JavaScript execution stack is empty
Example: Promises and Mutation Observer API
JS
Engines
and
Event
loop
overview
No
So, Is Javascript
asynchronous ?
Explanation
Yes
So, Is Javascript
Single Threaded ?
Explanation
References:
1. How Javascript works behind the scene
2. Event Loop - mozilla
3. Node event loop
4. Understanding JS- The event loop
5. Javascript Event Loop Explained
6. How does Javascript actually work
7. JavaScript: How It's Made - Youtube Video
8. Understanding Javascript Heap Stack, event loops and call back queue
9. What the heck is the event loop anyway? | Philip Roberts | JSConf EU
More on JS
1. Understanding execution context and execution stack in javascript
2. Javascript inside v8 engine and 5 tips to write optimized code
3. Memory Management to handle common memory leaks
4. Javascript Events Loops and rise of async programming
5. JavaScript. Event Loop and Promises
6. Micro tasks - Mozilla

Contenu connexe

Tendances

Asynchronous javascript
 Asynchronous javascript Asynchronous javascript
Asynchronous javascriptEman Mohamed
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event HandlingWebStackAcademy
 
Asynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesAsynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesHùng Nguyễn Huy
 
WebAssembly: In a Nutshell
WebAssembly: In a NutshellWebAssembly: In a Nutshell
WebAssembly: In a NutshellRangHo Lee
 
Coroutines in Kotlin
Coroutines in KotlinCoroutines in Kotlin
Coroutines in KotlinAlexey Soshin
 
Rust system programming language
Rust system programming languageRust system programming language
Rust system programming languagerobin_sy
 
gRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at SquaregRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at SquareApigee | Google Cloud
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js ExpressEyal Vardi
 
Spring boot Under Da Hood
Spring boot Under Da HoodSpring boot Under Da Hood
Spring boot Under Da HoodMichel Schudel
 
Reactive programming
Reactive programmingReactive programming
Reactive programmingSUDIP GHOSH
 
Why Rust? - Matthias Endler - Codemotion Amsterdam 2016
Why Rust? - Matthias Endler - Codemotion Amsterdam 2016Why Rust? - Matthias Endler - Codemotion Amsterdam 2016
Why Rust? - Matthias Endler - Codemotion Amsterdam 2016Codemotion
 
[JS EXPERIENCE 2018] Javascript Event Loop além do setInterval - Derek Stavis
[JS EXPERIENCE 2018] Javascript Event Loop além do setInterval - Derek Stavis[JS EXPERIENCE 2018] Javascript Event Loop além do setInterval - Derek Stavis
[JS EXPERIENCE 2018] Javascript Event Loop além do setInterval - Derek StavisiMasters
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJSBrainhub
 
Sharing Data Between Angular Components
Sharing Data Between Angular ComponentsSharing Data Between Angular Components
Sharing Data Between Angular ComponentsSquash Apps Pvt Ltd
 
An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...Claudio Capobianco
 

Tendances (20)

Asynchronous javascript
 Asynchronous javascript Asynchronous javascript
Asynchronous javascript
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event Handling
 
Asynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesAsynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & Promises
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
WebAssembly: In a Nutshell
WebAssembly: In a NutshellWebAssembly: In a Nutshell
WebAssembly: In a Nutshell
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
WebAssembly Overview
WebAssembly OverviewWebAssembly Overview
WebAssembly Overview
 
C# Async Await
C# Async AwaitC# Async Await
C# Async Await
 
Coroutines in Kotlin
Coroutines in KotlinCoroutines in Kotlin
Coroutines in Kotlin
 
Rust system programming language
Rust system programming languageRust system programming language
Rust system programming language
 
gRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at SquaregRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at Square
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 
Spring boot Under Da Hood
Spring boot Under Da HoodSpring boot Under Da Hood
Spring boot Under Da Hood
 
Reactive programming
Reactive programmingReactive programming
Reactive programming
 
Angular
AngularAngular
Angular
 
Why Rust? - Matthias Endler - Codemotion Amsterdam 2016
Why Rust? - Matthias Endler - Codemotion Amsterdam 2016Why Rust? - Matthias Endler - Codemotion Amsterdam 2016
Why Rust? - Matthias Endler - Codemotion Amsterdam 2016
 
[JS EXPERIENCE 2018] Javascript Event Loop além do setInterval - Derek Stavis
[JS EXPERIENCE 2018] Javascript Event Loop além do setInterval - Derek Stavis[JS EXPERIENCE 2018] Javascript Event Loop além do setInterval - Derek Stavis
[JS EXPERIENCE 2018] Javascript Event Loop além do setInterval - Derek Stavis
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
Sharing Data Between Angular Components
Sharing Data Between Angular ComponentsSharing Data Between Angular Components
Sharing Data Between Angular Components
 
An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...
 

Similaire à JavaScript Engines and Event Loop

Javascript why what and how
Javascript why what and howJavascript why what and how
Javascript why what and howsureshpraja1234
 
Javascript internals
Javascript internalsJavascript internals
Javascript internalsAyush Sharma
 
DevTools
DevToolsDevTools
DevToolsboucher
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScriptAmitai Barnea
 
Google App Engine for Java v0.0.2
Google App Engine for Java v0.0.2Google App Engine for Java v0.0.2
Google App Engine for Java v0.0.2Matthew McCullough
 
Isomorphic JavaScript with Nashorn
Isomorphic JavaScript with NashornIsomorphic JavaScript with Nashorn
Isomorphic JavaScript with NashornMaxime Najim
 
"Leveraging the Event Loop for Blazing-Fast Applications!", Michael Di Prisco
"Leveraging the Event Loop for Blazing-Fast Applications!",  Michael Di Prisco"Leveraging the Event Loop for Blazing-Fast Applications!",  Michael Di Prisco
"Leveraging the Event Loop for Blazing-Fast Applications!", Michael Di PriscoFwdays
 
Jdk Tools For Performance Diagnostics
Jdk Tools For Performance DiagnosticsJdk Tools For Performance Diagnostics
Jdk Tools For Performance DiagnosticsDror Bereznitsky
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkAarti Parikh
 
node.js 실무 - node js in practice by Jesang Yoon
node.js 실무 - node js in practice by Jesang Yoonnode.js 실무 - node js in practice by Jesang Yoon
node.js 실무 - node js in practice by Jesang YoonJesang Yoon
 
End-to-end HTML5 APIs - The Geek Gathering 2013
End-to-end HTML5 APIs - The Geek Gathering 2013End-to-end HTML5 APIs - The Geek Gathering 2013
End-to-end HTML5 APIs - The Geek Gathering 2013Alexandre Morgaut
 
"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
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipseanshunjain
 
Spark Streaming Recipes and "Exactly Once" Semantics Revised
Spark Streaming Recipes and "Exactly Once" Semantics RevisedSpark Streaming Recipes and "Exactly Once" Semantics Revised
Spark Streaming Recipes and "Exactly Once" Semantics RevisedMichael Spector
 
Stateful patterns in Azure Functions
Stateful patterns in Azure FunctionsStateful patterns in Azure Functions
Stateful patterns in Azure FunctionsMassimo Bonanni
 

Similaire à JavaScript Engines and Event Loop (20)

Javascript why what and how
Javascript why what and howJavascript why what and how
Javascript why what and how
 
Javascript internals
Javascript internalsJavascript internals
Javascript internals
 
DevTools
DevToolsDevTools
DevTools
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScript
 
Google App Engine for Java v0.0.2
Google App Engine for Java v0.0.2Google App Engine for Java v0.0.2
Google App Engine for Java v0.0.2
 
Isomorphic JavaScript with Nashorn
Isomorphic JavaScript with NashornIsomorphic JavaScript with Nashorn
Isomorphic JavaScript with Nashorn
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajax
 
"Leveraging the Event Loop for Blazing-Fast Applications!", Michael Di Prisco
"Leveraging the Event Loop for Blazing-Fast Applications!",  Michael Di Prisco"Leveraging the Event Loop for Blazing-Fast Applications!",  Michael Di Prisco
"Leveraging the Event Loop for Blazing-Fast Applications!", Michael Di Prisco
 
Jdk Tools For Performance Diagnostics
Jdk Tools For Performance DiagnosticsJdk Tools For Performance Diagnostics
Jdk Tools For Performance Diagnostics
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
 
Proposal
ProposalProposal
Proposal
 
Concurrency in ruby
Concurrency in rubyConcurrency in ruby
Concurrency in ruby
 
node.js 실무 - node js in practice by Jesang Yoon
node.js 실무 - node js in practice by Jesang Yoonnode.js 실무 - node js in practice by Jesang Yoon
node.js 실무 - node js in practice by Jesang Yoon
 
End-to-end HTML5 APIs - The Geek Gathering 2013
End-to-end HTML5 APIs - The Geek Gathering 2013End-to-end HTML5 APIs - The Geek Gathering 2013
End-to-end HTML5 APIs - The Geek Gathering 2013
 
"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 "
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipse
 
Spark Streaming Recipes and "Exactly Once" Semantics Revised
Spark Streaming Recipes and "Exactly Once" Semantics RevisedSpark Streaming Recipes and "Exactly Once" Semantics Revised
Spark Streaming Recipes and "Exactly Once" Semantics Revised
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
 
Stateful patterns in Azure Functions
Stateful patterns in Azure FunctionsStateful patterns in Azure Functions
Stateful patterns in Azure Functions
 

Dernier

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 

Dernier (20)

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

JavaScript Engines and Event Loop

  • 1. JS behind the scene (JavaScript Engines and Event loops ) Tapan B.K. Software Engineer Insight workshop btapaniw@gmail.com bktapan16@gmail.com +977-9849-716-660
  • 2. 1. Execution Context 2. Execution Stack 3. Variable Object 4. Scoping and the Scope Chain 5. The ‘this’ Keyword 6. Hoisting (function and variable) JS Behind the Scene also contains:
  • 3.
  • 6.
  • 7. What is JavaScript? 1. High level 2. Single threaded 3. Garbage collected 4. Interpreted or just-in-time compiled 5. Prototype-based 6. Multi-paradigm 7. Dynamic weakly typed language 8. With a non-blocking event loop
  • 8. What happens to our JS code? Summary: Our code -> parser -> no errors then parser produces abstract syntax tree -> converts it to machine code -> done conversion -> code runs
  • 9. Some Popular Javascript Engines V8: Used in Chrome and chromium-based browsers (Google) SpiderMonkey: Used in firefox (Mozilla) JavaScriptCore/Nitro : Used in safari browser (Apple) Chakra: Microsoft Edge and Internet Explorer (Microsoft) JerryScript: lightweight engine for Internet of things
  • 11. Call Stack Correction Note: Actual Output is 100
  • 12. Call Stack Explained 1. The call stack is a LIFO queue (Last In, First Out). 2. Stacks holds our function calls. On each new function call, it’s pushed on top of the stack 3. The event loop continuously checks the call stack to see if there’s any function that needs to run. 4. While doing so, it adds any function call it finds to the call stack and executes each one in order.
  • 14. Max Call Stack(Stack Overflow)
  • 15. Web API Some of the web APIs are: 1. Console API 2. Web storage API 3. DOM API 4. Drag and Drop API Full Lists of Web API Provides extra super Power to Developer
  • 17. Call back Queue / Event Queue The event loop facilitates this process; it constantly checks whether or not the call stack is empty. If it is empty, new functions are added from the event queue. If it is not, then the current function call is processed
  • 18. Event loops 1. The event loop is the secret behind JavaScript asynchronous programming. 2. JS executes all operations on a single thread, but using a few smart data structures, it gives us the illusion of multi-threading. 3. Event loops are not Javascript specific as they are handle by Browser. They do just in time compilation.
  • 19. Event Loop The event loop got its name because of how it's usually implemented, which usually resembles: queue.waitForMessage() waits synchronously for a message to arrive (if one is not already available and waiting to be handled).
  • 20. Event loops with the promises Output:
  • 21. Types of of asynchronous tasks: The macro tasks: 1. They are programmed so that the browser can ensure that they are executed sequentially when accessing from your internal engine to Javascript. 2. For example, callbacks of browser events (an onClick) or those of functions such as setTimeout
  • 22. Types of of asynchronous tasks: The microtasks: A microtask is a short function which is executed after the function or program which created it exits and only if the JavaScript execution stack is empty Example: Promises and Mutation Observer API
  • 25. Yes So, Is Javascript Single Threaded ? Explanation
  • 26.
  • 27. References: 1. How Javascript works behind the scene 2. Event Loop - mozilla 3. Node event loop 4. Understanding JS- The event loop 5. Javascript Event Loop Explained 6. How does Javascript actually work 7. JavaScript: How It's Made - Youtube Video 8. Understanding Javascript Heap Stack, event loops and call back queue 9. What the heck is the event loop anyway? | Philip Roberts | JSConf EU
  • 28. More on JS 1. Understanding execution context and execution stack in javascript 2. Javascript inside v8 engine and 5 tips to write optimized code 3. Memory Management to handle common memory leaks 4. Javascript Events Loops and rise of async programming 5. JavaScript. Event Loop and Promises 6. Micro tasks - Mozilla

Notes de l'éditeur

  1. Scripting Language famously written in 10 days High Level JavaScript is considered high-level because it does not require direct interaction with the operating system, hardware. In addition, it does not require memory-management like C/C++ because the runtime always uses garbage-collection. Interpreted or Just-in-Time Compiled Interpreted means the source code is converted to bytecode and executed at runtime (as opposed to being compiled to a machine code binary at build time). This is also why JS is commonly called a “scripting language”. Originally, it was only interpreted, but modern JS engines like V8, Spidermonkey, and Nitro use various techniques to perform Just-in-Time Compilation or JIT for better performance. Developers still use JS like an interpreted language, while the engine magically compiles parts of source code to low-level machine code behind the scenes. Multi-Paradigm Multi-Paradigm means the language is general-purpose or flexible. JS can be used for declarative (functional) or imperative (object-oriented) programming styles. Dynamic Weakly Typed Dynamic most often refers to the type system. JS is dynamic weakly typed language, meaning you do not annotate variables with types (string, int, etc) and the true types are not known until runtime. Prototypal Inheritance or prototype-based Prototypal Inheritance means that objects can inherit behaviors from other objects. This differs from classical inheritance where you define a class or blueprint for each object and instantiate it. Non-blocking event loop Single-Threaded means that JS can only run one instruction at a time. Event Loop refers to a feature implemented by engines like V8 that allow JS to offload tasks to separate threads. Browser and Node APIs execute long-running tasks separately from the the main JS thread, then enqueue a callback function (which you define) to run on the main thread when the task is complete. This is why JS is called non-blocking because it should only ever wait for synchronous code from your JS functions. Think of the Event Loop as message queue between the single JS thread and the OS.
  2. Inside the engine, our code is parsed by a parser, which basically reads our code line by line and checks whether the syntax of the code we gave it is correct. This implies that the engine knows the JavaScript rule, and how it has to be written in order to be correct/ valid. When we make some mistakes, it will throw errors and stop the execution, if everything is correct, then the parser produces a data structure known as Abstract Syntax Tree, which is then later translated to machine code. So this code is no longer JavaScript code, but a set of instructions that can be executed directly by the computer’s processor. When our code is finally converted to machine code then it will actually run and do its work.
  3. Web API, Callback Queue and Event Loop mechanisms are part of browsers Heap Heap is the place (memory) where objects are stored when we define variables and objects. Stack this is where your stack frames are as your code executes. The call stack is responsible for keeping track of all the operations in line to be executed. Whenever a function is finished, it is popped from the stack. You can see your stack when you have an exception on JavaScript by stack trace. Web API Browsers have defined API’s which developers can be used to make complex processes such as to get location of visitor, GeoLocation is defined. Callback Queue When a process finished its job, such as a xhr call, it’s dropped in a callback queue. Callback queue is triggered by event loop process after our stack is empty which means the process waits in that queue until our stack is empty. Once our stack has no function call, then a process is popped-out from callback queue and pushed in to stack. Event Loop A process which is responsible to check our stack and then trigger our callback queue continuously.
  4. var items = []; items.push(...new Array(1000000)); the number of recursive calls you can make depends on two quantities: the size of the stack and the size of the stack frame (holding parameters and local variables)
  5. Web API are built into your web browser, and are able to expose data from the browser and surrounding computer environment and do useful complex things with it. They are not part of the JavaScript language itself, rather they are built on top of the core JavaScript language, providing you with extra superpowers to use in your JavaScript code
  6. Every time you call a setTimeout function or you do some async operation — it is added to the Event Table. This is a data structure which knows that a certain function should be triggered after a certain event. Once that event occurs (timeout, click, mouse move) it sends a notice. Bear in mind that the Event Table does not execute functions and does not add them to the call stack on it’s own. It’s sole purpose is to keep track of events and send them to the Event Queue. The Event Queue is a data structure similar to the stack — again you add items to the back but can only remove them from the front. It kind of stores the correct order in which the functions should be executed. It receives the function calls from the Event Table, but it needs to somehow send them to the Call Stack? This is where the Event Loop comes in.
  7. An example of this is the setTimeout method. When a setTimeout operation is processed in the stack, it is sent to the corresponding API which waits till the specified time to send this operation back in for processing. Where does it send the operation? The event queue. Hence, we have a cyclic system for running async operations in JavaScript. The language itself is single-threaded, but the browser APIs act as separate threads. The event loop facilitates this process; it constantly checks whether or not the call stack is empty. If it is empty, new functions are added from the event queue. If it is not, then the current function call is processed
  8. It’s a way to execute the result of an async function as soon as possible, rather than being put at the end of the call stack. Promises that resolve before the current function ends will be executed right after the current function. I find nice the analogy of a rollercoaster ride at an amusement park: the message queue puts you at the back of the queue, behind all the other people, where you will have to wait for your turn, while the job queue is the fastpass ticket that lets you take another ride right after you finished the previous one.
  9. These microtasks are stored into the microtask queue Each time a task exits, the event loop checks to see if the task is returning control to other JavaScript code. If not, it runs all of the microtasks in the microtask queue. The microtask queue is, then, processed multiple times per iteration of the event loop, including after handling events and other callbacks.. Exampls of micro tasks are promises.
  10. When a process finished its job, such as a xhr call, it’s dropped in a callback queue. Callback queue is triggered by event loop process after our stack is empty which means the process waits in that queue until our stack is empty. Once our stack has no function call, then a process is popped-out from callback queue and pushed in to stack.
  11. JavaScript is always synchronous and single-threaded. If you're executing a JavaScript block of code on a page then no other JavaScript on that page will currently be executed. JavaScript is only asynchronous in the sense that it can make, for example, Ajax calls. The Ajax call will stop executing and other code will be able to execute until the call returns (successfully or otherwise), at which point the callback will run synchronously. No other code will be running at this point. It won't interrupt any other code that's currently running.
  12. JavaScript is always synchronous and single-threaded. If you're executing a JavaScript block of code on a page then no other JavaScript on that page will currently be executed. JavaScript is only asynchronous in the sense that it can make, for example, Ajax calls. The Ajax call will stop executing and other code will be able to execute until the call returns (successfully or otherwise), at which point the callback will run synchronously. No other code will be running at this point. It won't interrupt any other code that's currently running.