Day #9 Pro Tip #Javascript
Block level scope in Javascript !!!
Published in
1 min readApr 10, 2018
Let us consider this example
function scope() { var scope = "I am outer scope" if(true){
var scope = "I am inner scope"
console.log(scope) //This would print I am inner scope
}
console.log(scope) //This would also print I am inner scope
}
This happens because unlike other languages which have default block level scope Javascript doesn’t provide that. But no worries there is a way to have block level scope of the variables using let keyword for variable declaration. So block level scope in the above example can be achieved in the following way
function scope() { let scope = "I am outer scope" if(true){
let scope = "I am inner scope"
console.log(scope) //This would print I am inner scope
}
console.log(scope) //This would also print I am outer scope
}
Thanks for reading :)
Stay tuned for more updates !!!