Member-only story
JS Essentials: The JavaScript Engine
Everything you need to know about the JavaScript engine, scopes, closures, the event queue, and how to apply this knowledge.
Table of Contents
— Prerequisites
— Definitions
— The Call Stack
— — 1. Variable & Function Declarations (creation phase)
— — 2. Execution
— Scope and The Scope Chain
— — Function/Lexical Scope
— — Block Scope
— The Event Loop
— Code Examples
— — Simple Closure
— — Blocking Code
— — Defer a Function
— — Memoize with Closures
— Resources and Links
Prerequisites
You only need a basic knowledge of JavaScript. While this seems like an advanced tutorial, it’s one of the fundamental concepts of JS that you should learn early to save a lot of time debugging later.
Definitions
There will be a lot of terms used here so let’s get them out of the way early. For our purposes, we’ll use simplified definitions and go in depth later.
(JavaScript) Engine — a program that reads your code, decides if it’s valid and runs it. There is no single “JS Engine”; each browser has its own engine. i.e. Google has V8
Scope — the “area” you can access a variable from.
Lexical Scope — scope determined by where the running piece of code physically sits in your source-code. Anytime I say lexical or lexically I mean where it’s literally sitting inside your code.
Block Scope — scope created by curly braces {}
Scope Chain — a function can go up to its outer environment (lexically) to search for a variable, it can keep going until it reaches the global environment. We call this going up the scope chain.
Global — not inside a function, available anywhere.
Synchronous — one thing at a time; a “synchronous” engine only executes one line at a time. JavaScript is synchronous and executes code line by line starting at the top of the file.
Asynchronous — multiple things at a time; JS emulates async behavior via browser APIs