Truths About JavaScript  Only EXPERTS Know

Truths About JavaScript Only EXPERTS Know

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.