Hoisting is a phenomenon in javaScript by which you can access variables and functions even before you have initialized them or you have put some value on them. you can access it without any error.
Hoisting allows functions to be safely used in code before they are declared.
for Example:
var x=7; function getName(){ console.log("hoisting in javaScript"); } getName(); console.log(x); expected output: hoisting in javaScript , 7
even trying to access x before initialization and call a function before initialization most of the programing language will result out be an error, you can not access the variable before initialization.
for Example:
getName(); console.log(x); var x=7; function getName(){ console.log("hoisting in javaScript"); }
output: hoisting in javaScript, undefine
Function hoisting
for Example:
getName(); console.log(x); console.log(getName); var x=7; function getName(){ console.log("Hoisting in javaScript"); }
outPut: Hoisting in javascript, undefine,
function getName(){ console.log("Hoisting in javaScript"); }
In case of x getting undefine and in case of getName printing, that function whenever we run javaScript program is executed context is created. It is created in two phases the first phase is the memory creation phase and the second is the Execution Phase.
Even before the whole code execution in javaScript, the memory is allocated to each and every variable and function and stores the particular keyword for the variable “undefine.”
Even before the code execution javaScript reserved memory for x and placed the special place holder “undefine” to it and similarly, what happens in the case of function the whole code is putting
Arrow Function:
getName(); console.log(x); console.log(getName); var x=7; var getName=()=>{ console.log("hoisting in javaScript") } output: TypeError / getName is not a function
now getName is not behaved as a function it behaves just like a variable even before executing the whole code so know when in the memory allocation phase of the execution context getName allocates undefine
Summary: –
- Now you have learned how to work Hoisting in JavaScript.
- It helps to access variables and functions before the declaration
- If you are working on a framework/library like React Js you will be using variable and function