Hoisting in JavaScript
Hoisting is a phenomena in JavaScript by which you can access variables and function even before you have initialized it or access it without any error.
a()console.log(x)var x = 'kolhe';function a() {console.log('shreyash');}
undefined shreyashJavaScript first declaring the variable and then initializing it. remember the execution context, even before the code starts executing memory is allocated to this all variable and function. means all variables and function store in memory component then it initialized.
supposed, we initialized code then declared variable what’s will happened?
yes, it shows undefined. but Why?console.log(x)var x = 'shreyash'
because when js code is run Global execution context will created. in first phase, it allocate all the variable and function in memory component and put undefined . then second phase will start this is code execution phase. in this execute js code line by line and replace the undefined to it's actual value and perform all calculations.
but
In our case the we did call x variable before its declare so it doesn't found actual value in memory component that's why it shows undefined.
but in the case of function it act totally different...
function is a heart of JavaScript, it nothing show an error or not shows undefined because JavaScript function are independent nature. it has not any restriction. when function call it execute the function directly.a();function a(){console.log('shreyash');}
suppose we put the function in variable … what’s will happened?
yes it work like function but suppose we call a variable function before initialization. likevar a = () =>{console.log('shreyash');}console.log(a);
so this time, a print undefined because this function is behave or act like a variable. it does not behave like a function. In the memory allocation phase of the execution context it allocate undefine.console.log(a)var a = () => {console.log('shreyash');}
That’s all about hoisting
Post a Comment