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.
keywordlet
andconst
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
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
function loop(){
for(let i = 0; i < 5; i++){
console.log(i)
}
console.log('final', i)
}
loop() // Reference Error, i is not defined
Top comments (0)