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";
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";
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
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"
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;
}
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.
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
AH AH! so, here you're!
and the same happens with const:
function test(){
return confusing;
const confusing = "Still Safe!";
}
console.log(test())
Can you guess, what happens with "let" and "const" in the global scope?
Because let is a "block scope local variable" and you need to put it into a block to unleash it's power...
Top comments (0)