Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo
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:
JavaScript Engines and Event Loop
Expected Output:
But actual Output is
JavaScript Engines and Event Loop
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
JavaScript Engines and Event Loop
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

More Related Content

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:
  • 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
  • 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

Editor's Notes

  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.