DEV Community

Cover image for Too quick, What hoisting really is ?
Wassim Ben Jdida
Wassim Ben Jdida

Posted on

Too quick, What hoisting really is ?

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;
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (2)

snehag_07 profile image

Why did the variable logged as undefined?

wassimbj profile image
Wassim Ben Jdida

because before the javascript engine starts executing your code it sets up a memory space of all the variables in your code as "undefined", thats hoisting.