Understand the Components of the Event Loop
function foo() {
return function bar() {
return function baz() {
return 'I love CodeCademy'
}
}
}
console.log(foo()()());
The Heap
The heap is a block of memory where we store objects in an unordered manner. JavaScript variables and objects that are currently in use are stored in the heap.
The Call Stack
The Call Stack, or call stack, tracks what function is currently being run in your code.
When you invoke a function, a frame is added to the stack. Frames
connect that function’s arguments and local variables from the heap. Frames enter the stack in a last
in, first out (LIFO) order. In the code snippet below, a series of nested functions are declared,
then foo()
is called and logged.
The event loop is made up of these parts:
- Memory Heap
- Call Stack
- Event Queue
- Event Loop
- Node or Web APIs
Concurrency in JavaScript
Usually when we think about concurrency in programming, it means
that two or more procedures are executed at the same time on the same shared resources. Since JavaScript is
single-threaded, as we saw in the for
loop example, we’ll
never have that flavor of “true” concurrency. However, we can emulate concurrency using the event loop.
What Is the Event Loop?
At a high level, the event loop is a system for managing code execution. In the diagram, you can see an overview of how the parts that make up the event loop fit together.
We have data structures that we call the heap and the call stack, which are part of the JavaScript engine. The heap and call stack interact with Node and Web APIs, which pass messages back to the stack via an event queue. The event queue’s interaction with the call stack is managed by an event loop. All together, those parts maintain the order of code execution when we run asynchronous functions. Don’t worry about understanding what those terms mean yet–we’ll dive into them shortly.