Did you know that JavaScript allocates memory to all variables and functions first, even before executing the code?
Yes, that's true. And this results in a phenomenon called "hoisting" in JavaScript.
Hoisting allows us to use variables and functions even before they're declared. Look at this example
console.log(x);
var x = 'sample';
Interestingly, this will not throw an error. Instead, it will output undefined
. Let's take a slightly deeper dive into this process.
Variable hoisting
The interpreter hoists variables declared with
var
with a default value of "undefined". Therefore, If you use a variable declared withvar
before it's been declared, it will returnundefined
.The interpreter also hoists variables declared with
let
orconst
, but this time, the variables are not assigned a default value. JS just knows that these variables exist in the code. Therefore, If you use a variable declared with let/const before it's been initialized, it will throw an error stating "cannot access xyz before initialization".If you don't initialize the variable anywhere in the code, and try to use such variable, it will throw an error stating "xyz is not initialized". See how this time JS doesn't even know that xyz exists.
Function hoisting
- Unlike variables, an actual copy of the function is hoisted at the time of memory allocation. This gives an advantage of using calling functions even before they've been initialized.
- Note that if you assign a function to a variable (like in arrow functions), it will no more be treated as a function. Just how variables are hoisted by a default value of undefined, this function will also be treated the same.
Want to read a detailed explanation with more examples, check out this amazing article by Zach Snoek on FreeCodeCamp's website.
Happy coding :)
#10daysofJSfundamentals (DAY 7)