Too quick, What hoisting really is ?
Wassim Ben Jdida
Posted on February 4, 2021
Simply, Hoisting in javascript is a memory space that the javascript engine sets up before executing your code.
it sets up a memory space for your variables and functions, that's what explain when you call your function and then actually create it, works.
code example:
add(2, 2) // this will work fine and it will return 4
function add(a, b){
return a + b;
}
console.log(x); // this will return "undefined"
var x;
if you rewrite this code in languages like python, php or go, it will throw an error, because the function is called before its defined and the variable too.
but as I said before, the javascript engine creates a memory space for your functions and variables too and it sets the value of the variables as "undefined".
so when the javascript engine start to execute your code it sees the add()
function, and it recognize it cause its already in its memory, so it execute it without any issues, and for the variable too, it sees the x
variable and it recognize it, but the value is set to "undefined" by default so it returns it.
some articles say that the javascript engine moves the variables and functions to top, thats not it, javascript engine doesn't do that, it just remember them cause they are already in its memory.
Posted on February 4, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.