YogeshChauhan . com

What is Hoisting in JavaScript?

in JavaScript on February 27, 2020

Hoisting is JavaScript's default behavior of moving declarations to the top.

In JavaScript, a variable can be declared after it has been used. In other words; a variable can be used before it has been declared.

Let's take a look at the examples below.


//Example 1
x = 5; // Assign 5 to x
elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x; // Display x in the element
var x; // Declare x

In the example above we are declaring the variable after assigning value and even using it. The following example gives same result as well when you declare the variable first and then use it.


//Example 2
var x; // Declare x
x = 5; // Assign 5 to x
elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x; // Display x in the element

As I have mentioned earlier, Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).

Variables and constants declared with let or const are not hoisted!

JavaScript Initializations are Not Hoisted either!


//Example 3
var x = 5; // Initialize x
var y = 7; // Initialize y
elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x + " " + y; // Display x and y

//Example 4
var x = 5; // Initialize x
elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x + " " + y; // Display x and y
var y = 7; // Initialize y

We need to declare your variables at the top! Why? Because Hoisting is an unknown or overlooked behavior of JavaScript. If we, as developers, don't understand hoisting, programs may contain errors. To avoid any types of bugs and errors, it's a great practice to declare all variables at the beginning of every scope. Since this is how JavaScript interprets the code, it is always a good rule to follow.

amazon

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

How to solve “framework not found” error in Swift?SwiftHow to create a simple tab interaction using CSS?CSSSolution for “Yarn build: Failed because of a stylelint error”WordPressHow to get category name using post id in WordPress?WordPressKeyValuePipe in Angular 9AngularHow different is Handling Events in React vs HTML DOM?React