YogeshChauhan.com
What is Hoisting in JavaScript?
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.

dreamhost

Leave a Reply

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to set opacity or transparency using CSS? #3 Pagination in CSS with multiple examples #4 How to make HTML form interactive and using CSS? #5 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #6 How to uninstall Cocoapods from the Mac OS?



Recently Posted

Feb 27 WordPress: How to display slider repeater fields in ACF? Feb 26 Simple Page Hit Counter in PHP Feb 26 Here’s what we can do with PHP date() function Feb 25 How to set default timezone using PHP? Feb 24 WordPress: How to loop through a repeater field in ACF? Feb 24 How to get ACF values from custom post type?



You might also like these

LIMIT and OFFSET in PostgresPostgresList of all Pseudo Elements in CSSCSSHow to detect the Blog Page in WordPress?WordPressWHERE Clause in PostgresPostgresHow to set the permissions on all files and folders in Mac?MiscWhat is a Strict Requirement in PHP 7 Function Declarations?PHP