JavaScript Hoisting. Learn Everything You Need To Know

Posted by TotalDC

Last time you learned about borrowing methods in JavaScript. In this tutorial we will talk about JavaScript hoisting.

What Is Hoisting In JavaScript

As you know, in JavaScript all variable and function declarations are moved or hoisted to the top of their current scope, no matter where it is defined. This is the default behavior of JavaScript interpreter which is called hoisting.

Function Hoisting In JavaScript

Functions that are defined using a function declaration are automatically hoisted. That means that they can be called before they have been defined. Here’s an example for you:

// Calling function before declaration
sayHello(); // Result: Hello, I'm hoisted!

function sayHello() {
    console.log("Hello, I'm hoisted!");
}

In this example the sayHello() function is called before it is defined, but the code still works. This is because the function declaration is hoisted to the top automatically behind the scenes.

Variable Hoisting In JavaScript

Variable declarations are also hoisted to the top of their current scope automatically. This means that if the variable is declared inside a function block, it will be moved at the top of the function, but if it is declared outside any function it will be moved to top of the script and become globally available. Here’s how it looks:

str = "Hello World!";
console.log(str); // Result: Hello World!
let str;

JavaScript only hoists declarations, not initializations. That means if a variable is declared and initialized after using it, the value will be undefined. Let’s look at the example:

console.log(str); // Result: undefined
let str;
str = "Hello World!";

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: