Scope in Block Statements
Scope in Block Statements
- Block statements like
if
and switch
conditions or for
and while
loops, unlike functions, will create a new scope if you use let
or const
but NOT when you use var
Example
- Declaring a variable within a Block statement using
let
creates local scope
if (true) {
// this 'if' conditional block creates a new scope because we use 'let'
const name = 'Prince' // name is local to the if block
console.log(name) // logs 'Prince'
}
console.log('----')
console.log(name) // <--- error because the 'name' variable can only be accessed from within the block (due to the use of 'let')
JS Bin on jsbin.com
- Declaring a variable within a Block statement using
var
DOES NOT create local scope
if (true) {
var name = 'Prince' // declare a variable using 'var`
console.log(name) // logs 'Prince'
}
console.log('----')
console.log(name) // <--- logs 'Prince' because the 'name' variable is in the global scope due to the use of `var`
JS Bin on jsbin.com