JavaScript has function scope (lexical scope) every time we create a function we create a new execution context which has its own variable environment. However, most other programming languages have something called block scope
.
Function Scope
var isValid = false
if(!isValid){
var function_scope = true
}
console.log(function_scope)
true
- no error
Block Scope
var isValid = false
if(!isValid){
let block_scope = true
}
console.log(block_scope)
ReferenceError: block_scope is not defined
JavaScript with After ES6 let
, const
keywords they allow us to use block scoping.
Actually, the variable itself let
, const
still in memory, but the JavaScript engine do not allow you to access it.