What is javascript hoisting?
If you are javascript learner you might have heard the word hoisting. Let me explain about hoisting in below examples. There are a lot of tutorials where hoisting is explained as declaring the variables or functions on top of all other codes. We can partially accept it. But it's important to understand the real explanation of it, it's just adding the variables or functions in memory during compile time.
Javascript hoisting in function
//function declaration
function myFun(webname)
{
console.log(webname)
}
//invoking a functions
myFun(‘Programmer first’); // Programmer first
The above example will log whatever we are passing it in our function arguments. What if we declare the function after invoking it.
//invoking the functions
myfuninvoke(‘Javascript hoisting’); // Javasciprt hoisting.
//function declaration
function myFuninvoke(tech)
{
console.log(tech);
}
surprisingly the above example executes and prints the function argument in the console. Yeah! The function declaration is hoisted during compile time. So during the runtime when the function gets invoked it logs the result.
Javascript hosting in variables
Look at the below example in the variable declaration.
var a = 10;
console.log(a); // 10
what if we declare the variable at the bottom of our code.
x = 10;
console.log(x); //10
var x;
As you see in the image the output is 10.
What about this example, where we declare and initialize our variable at the bottom of our code?
console.log(x); //undefined
var x = 10;
we expected 10 but its prints undefined in the console. It’s because JavaScript only hoists declarations. Initializations are not hoisted.
If we declare variable and initialize it then only the variable declaration will be hoisted and the initialization will not be added in memory during compile time. The variable declared but it's not initialized, it automatically sets undefined. What if we write the previous code like below:
var x;
console.log(x); // undefined.
x=”Javascript hoisting”;
will get the same result.
Because of hoisting, it’s considered a best practice to always declare your variables at the top of their respective scopes/functions. This way there are no undesirable outputs. You should also always try to initialize variables when you declare them. This will avoid undefined variables and provides a better understanding when someone reads your code.
Don't get confused with 'undefined line's from the above images. it's just initializing the function/variable with undefined as it's not initialized with values. The above examples executed using
jsconsole. you can also use browser console to experiment it