Hoisting in JavaScript is a concept that moves all variable declarations and function declarations to the top of the script in the current scope before execution.

In simple words, hoisting allows one to use variables and call functions before they’re even declared. This concept is absolutely essential to understand for a beginner. If not understood, this can cause unwanted bugs in your code!

Note: Only declarations are hoisted and not initializations.

In this article, I will be writing about how hoisting works for functions. I have already written about how hoisting affects the usage of var, let and const in my article Difference between var, let and const.

Therefore I would not be going into details for the same. Nevertheless, here’s the summary:

  1. var: Only the variable declarations are hoisted to the top of their current scope and assigned a value undefined. Using them before declaration would just return undefined.
  2. let and const: These too are hoisted, however unlike var they are not initialized with any value. Using them before declaration would throw a reference error.

Hoisting with functions

In JavaScript, we can call a function before even declaring or defining it and it would run without any errors! Doing the same in another programming language would lead to your code being riddled with errors! This is all because of hoisting.

Functions in JavaScript can be classified as Function Declarations and Function Expressions. Hoisting works differently for both.

#javascript #computer-science #programming #coding

Understanding Hoisting in JavaScript
1.10 GEEK