Variable Scope
Variable scope means where a variable can be recognized and accessed.
Main Types
| Scope | Meaning |
|---|---|
| global scope | available across the whole script |
| local scope | available only inside a function or block |
| block scope | available only inside {} when declared with let or const |
Example
let globalName = "SpongeBob"
function greet() {
let message = "Hello"
console.log(message)
console.log(globalName)
}
greet()
console.log(message) // ReferenceError: message is not definedRemember
letandconstare block-scoped.varis function-scoped.- Prefer
letandconstbecause their scope is easier to reason about.