DEV Community

Discussion on: Javascript Hoisting

Collapse
 
copleykj profile image
Kelly Copley

"Let and const are hoisted in block scope whereas var is hoisted in global scope."

Actually var declarations are hoisted in function scope, and variables that are initialized without var, let or const are hoisted globally.

Collapse
 
naveenchandar profile image
Naveenchandar

Yep missed that one. That depends on the declaration. If that's inside particular block, it'll not get hoisted globally and if not, Let or const will be hoisted globally but due to temporal dead zone we can't access those until initialization.
"Let and const are hoisted in block scope whereas var is hoisted in global scope." -> Whenever we try to re declare a same variable using var inside a specific block, variable will get updated and that's not the same case with let because it is block scope so it will not be available outside the scope.
Example:

let greeting = "Hello";
    if (true) {
        let greeting = "Hi";
        console.log(greeting); // "Hi"
    }
    console.log(greeting); // "Hello"
Enter fullscreen mode Exit fullscreen mode
var greeting = "Hi";
    if (true) {
        var greeting= "Hello!";
        console.log(greeting); // "Hello!"
    }
    console.log(greeting); // "Hello"
Enter fullscreen mode Exit fullscreen mode
Collapse
 
christianbarnabechabi profile image
Christian Barnabé

Not sure about this

Collapse
 
copleykj profile image
Kelly Copley

You mean you were unsure about this, but then you read my comment. Now you know and are no longer unsure 😉