DEV Community

Mavis
Mavis

Posted on

Function scope vs Block scope

Function Scope

When declare a variable inside a function, it only can be used inside this function, and can not be used outside this function.

Block Scope

When declare a variable inside a {}, it can not be used outside the block.
keyword let and const was introduced since ES6, and provide Block Scope fro JavaScript.

Example
if ( 5 > 4 ) {
    var secrete = '123'
}
console.log(secrete) // 123, as js do not have block scope

function a () {
    var aSecrete = '123'
}
console.log(aSecrete) // Reference error
Enter fullscreen mode Exit fullscreen mode
function loop(){
    for(var i = 0; i < 5; i++){
        console.log(i)
    }
    console.log('final', i) // i got hoisted
}
loop() // 0, 1, 2, 3, 4, 5
Enter fullscreen mode Exit fullscreen mode
function loop(){
    for(let i = 0; i < 5; i++){
        console.log(i)
    }
    console.log('final', i)
}
loop() // Reference Error, i is not defined
Enter fullscreen mode Exit fullscreen mode

Top comments (0)