MediumJavascript Hoisting. Whenever we write some code, we assume… | by Pasindu Himal | Medium
Sitemap
Press enter or click to view image in full size

Javascript Hoisting

--

Whenever we write some code, we assume that the computer will understand it the way we have coded it, line-by-line. However, there is something special about how JavaScript works in this regard. Before your JavaScript executes the very first statement you write in the code, the engine does something behind-the-scenes known as hoisting, which is vital for developers to know.

To put it simply, hoisting explains why the order in which you write your code doesn’t strictly determine how the computer reads it. During a hidden creation phase, the JavaScript engine lays out all your function and variable declarations in memory before executing anything. This gives you the flexibility to write a helper function at the bottom of your file while confidently calling it at the top. The engine has already done the preparation, making your code adaptable, but it can also lead to unexpected bugs if you don’t know the rules.

Variable Hoisting

Variable hoisting is a JavaScript behavior where variable declarations are moved to the top of their scope before the code is executed. This does not mean the actual values are moved; only the declarations are hoisted. Because of this, a variable can sometimes be referenced before it appears in the code. Variables declared with var are hoisted and automatically initialized with undefined, while variables declared with let and const are also hoisted but cannot be accessed before their declaration due to the "Temporal Dead Zone" (TDZ). Understanding hoisting is important because it helps developers predict how JavaScript executes code and avoid unexpected errors.

Example:

console.log(name); // undefined
var name = "John";
console.log(name); // John

In this example, JavaScript behaves as if the declaration var name; was moved to the top of the scope before execution. Therefore, the first console.log() does not cause an error; instead, it prints undefined because the variable exists but has not yet been assigned a value. After the assignment name = "John", the second console.log() outputs "John".

Function Hoisting

Function hoisting is a JavaScript behavior where function declarations are moved to the top of their scope during the creation phase of execution. This allows a function declared using the function keyword to be called before its actual position in the source code. Unlike variable hoisting with var, where only the declaration is hoisted and the value remains undefined, a function declaration is hoisted together with its complete definition. As a result, JavaScript already knows about the function and its body before any code is executed. This behavior can make code more flexible, but developers should still place function declarations in a logical order to improve readability and maintainability.

Get Pasindu Himal’s stories in your inbox

Join Medium for free to get updates from this writer.

Example:

greet();
function greet() {
console.log("Hello, World!");
}

In the above example, the function greet() is called before its declaration appears in the code. Despite this, the program runs successfully and prints "Hello, World!" to the console. This happens because JavaScript hoists the entire function declaration during the compilation phase, making it available throughout the scope before execution begins.

It is important to note that function hoisting works differently for function expressions. When a function is assigned to a variable, only the variable declaration is hoisted, not the function itself. Therefore, attempting to call the function before the assignment takes place can result in an error.

Example of a function expression:

sayHello(); // Error
var sayHello = function () {
console.log("Hello!");
};

In this case, the variable sayHello is hoisted and initialized with undefined, but the function assignment does not occur until the execution reaches that line. When sayHello() is called before the assignment, JavaScript attempts to execute undefined as a function, resulting in an error.

Understanding function hoisting helps developers write more predictable JavaScript code and better understand how the JavaScript engine processes declarations before execution. It also highlights the difference between function declarations and function expressions, which is a common source of confusion for beginners.

Function hoisting is a key concept that helps developers understand how JavaScript processes code before running it. By learning the difference between function declarations and function expressions, you can avoid common mistakes and write more predictable, reliable programs. Although hoisting may seem confusing at first, it gets easier to grasp with practice and experimentation.

Thank you for reading! I hope this article helped you understand function hoisting and how it works behind the scenes in JavaScript. Keep exploring, coding, and building great things.

We’ll meet again next week to explore another important JavaScript concept. We’ll continue discovering the powerful features that make JavaScript one of the most popular programming languages in the world. Until then, happy coding and see you in the next article!

--

--

Pasindu Himal
Pasindu Himal

Written by Pasindu Himal

0 followers

B.Sc. (Hons.) Software Engineering | Full Stack Developer | AWS | Azure | Automation | AI | SW Architecture