Do you understand precompilation in JavaScript?

Shawn King
5 min readJun 5, 2024

Overview

Precompilation refers to the operations performed by the interpreter on the code before it is executed. There are mainly two operations: variable declaration and function declaration. The reason for these two operations is to ensure that undeclared variables can be used in advance during code execution.

Understanding the underlying compilation principles in JavaScript is essential. Through several examples, we will explore and learn about the foundational principles of precompilation in JavaScript. First, we should understand what the concept of precompilation is.

Example One

console.log(a)
var a = 0;

Some might say: Would anyone still write code like this? Isn’t this an obvious mistake? The compiler will definitely throw an error…
But the fact is: the compiler does not throw an error, it just outputs undefined. So some may wonder why it does not throw an error when the definition of the variable is after the output. This is because of an operation in JavaScript’s precompilation: hoisting.

Hoisting includes two types: variable declaration and function declaration.

  1. Variable declaration: Hoisting moves the declaration to the top, allowing the variable to be declared…

--

--

Shawn King

Focusing on front-end development and internet writing. Sharing technical tutorials and original fiction. https://skstory.online/