DEV Community

Fabio Russo
Fabio Russo

Posted on

What the... hoisting?

Hoisting in Javascript... has always been a really bad behavior of the language itself.

Why are you doing this for me?

If you dunno what I'm talking about, that's what (in short words) the hoisting is:

console.log(test)
// -> undefined
var test = "I'm not here";
Enter fullscreen mode Exit fullscreen mode

As you can see, when I'm calling the console.log(test) the variable itself, has not been declared at all!.

But Javascript is a bad guy that chooses to declare it for you.
Here's what happened:

//javascript will declare the variable, moving it at the TOP of it's scope
var test;
console.log(test)
// -> undefined
test = "I'm not here";
Enter fullscreen mode Exit fullscreen mode

this is really confusing, and should not happen at all!.

And we've not finished yet, because this also happens into function's scope.
Like this:

function test(){
  return test;
  var test = "I'm not here";
}

console.log(test())
// -> undefined
Enter fullscreen mode Exit fullscreen mode

And also happening with a function itself!.

If we move the call to console.log(test) at the top of the call stack, the
function test() should not exists...

console.log(test())

function test(){
  var test = "I should not be here";
  return test;
}

// -> "I should not be here"
Enter fullscreen mode Exit fullscreen mode

Nothing to do... Javascript is moving the function to the top of the Scope... so you can call a function, before you declare it...

But wait:

console.log(test)
// -> undefined
var test =function test(){
   var test = "I'm not here";
   return test;
}
Enter fullscreen mode Exit fullscreen mode

Why there's an undefined if we can call a function, before we declare it?

Because, in this last code, only the var test declaration has been moved to the top, and not the function assigned to It.

Let's RECAP!

Everytime you declare a var into a scope or write a function declaration, Javascript HOISTING moves those at the TOP of their scope without their value.

No way... I'm leaving!

alt text

So... "Let" and "Const" ...they are our salvation!

Let's look at what happens with Let and Const if we try to do the same dirty stuff:

function test(){
    return confusing;
    let confusing = "Finally!";
}

console.log(test())
//-> ReferenceError: can't access lexical declaration `confusing' before         initialization
Enter fullscreen mode Exit fullscreen mode

AH AH! so, here you're!

and the same happens with const:

function test(){
    return confusing;
    const confusing = "Still Safe!";
}

console.log(test())
Enter fullscreen mode Exit fullscreen mode

Can you guess, what happens with "let" and "const" in the global scope?

alt text

Because let is a "block scope local variable" and you need to put it into a block to unleash it's power...

But this is another story

alt text

Latest comments (0)