Truths About JavaScript Only EXPERTS Know

Mehak BaharMehak Bahar
2 min read

A wonderful attribute of JavaScript that I recently came across throughout my learning journey is the ability to call a function in JavaScript code even before it has been declared. But how is this possible? the very concept of "HOISTING"!

WHAT IS HOISTING?

Hoisting is basically a behavior shown by some programming languages, notably JavaScript, where all the variable or function declarations are moved or hoisted on the top of the code during compilation time.

In Simple Analogy

Think of it as the vocabulary of words used in a story, written at the top of a chapter. You already know about the words that are to be used in the story even before reading it.

Similarly, the JavaScript engine moves or hoists all the declarations of functions or variables to the top of the code, and then the whole code is read.

NOTE: Only the declarations of variables are moved to the top, not the initializations. Wherever the variable is initialized, It remains at that point in the code.

Following are some examples:

Function Hoisting:

The function sayHello(); is hoisted to the top allowing you to call the function even before it is positioned in the code.

sayHello();//output will be "Hello"

sayHello = () => {
  console.log("Hello!");
}

Variable Hoisting:

Note that only the declarations of the variables will be hoisted and not the initializations. Let me elaborate on my point with an example of JavaScript code:

console.log(x);//output will be undefined but will not throw an error
var x = 5;
console.log(x);//output will be "5"

As the declaration is hoisted at the top, it will not throw an error.


Drop a comment if you require further assistance or have any queries.

0
Subscribe to my newsletter

Read articles from Mehak Bahar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Mehak Bahar
Mehak Bahar

Hey there! I'm Mehak Bahar, navigating the tech world and sharing the real deal over. Think of this space as my tech diary, where I spill the beans on the highs and lows. Currently knee-deep in web development and design, I'm all about sharing the nitty-gritty - from coding mishaps to those 'aha' moments. But it's not just about tech glitches; I've got my eyes set on the AI realm too. This journey is more than just lines of code; it's a ride filled with challenges, victories, and a sprinkle of geeky fun. So, fellow tech enthusiasts, let's dive into this adventure together!