This content originally appeared on DEV Community and was authored by therealsuhail
Hey geeks, today let's read about hoisting in JS.
Hoisting is one of those fundamentals which i feel every JS developer should know.
In simple terms, hoisting allows you to use functions and variables before they are declared.
Let us look at the code below
console.log(name)
var name = 'hello JS'
In this case, JS will not throw any error rather it outputs 'undefined'. This is what hoisting is all about. It happens since JS allocates memory to variables and functions followed by the execution. In the memory allocation phase, variable name is being initialized with undefined , that is why it does not throw any error. Knowing about execution context will help you understand hoisting in a better way. You can check my article on execution context here
Variable hoisting
Variable hoisting behaves differently depending on how the variables are declared. Let us take a look at the code below
console.log(testVar)
let testVar = 'hello JS'
It is quite surprising that it throws a reference error unlike var. const also exhibits the same behaviour. we get such errors when let and const are in temporal dead zone. Temporal dead zone is nothing but the time between the variable is declared and assigned value.
let and const were introduced in ES5 to avoid using variables before their declaration. It is to be noted that interpreter hoists let and const, but in some other memory space, whereas in case of var it is hoisted in global execution context.
Function hoisting
Functions are also hoisted in the same way like variables. Let us take a look at the following code.
getName()
function getName() {
console.log("function")
}
Here it outputs 'function' since getName is allocated memory before execution.
let us look at another example
getName()
const getName = () => {
console.log("Inside function")
}
Here you will be surprised to see that it throws reference error unlike the previous example. It is because 'getName' behaves like a variable here. Only function declarations are hoisted and not function statements.
This content originally appeared on DEV Community and was authored by therealsuhail
therealsuhail | Sciencx (2022-06-27T15:26:06+00:00) Hoisting in JS. Retrieved from https://www.scien.cx/2022/06/27/hoisting-in-js/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.