Variable Declaration Scope in JavaScript
Variable Declaration Scope in JavaScript
Variable scope in JavaScript determines where variables can be accessed or referenced. This
document explores the different types of scope in JavaScript.
Types of Scope
1. Global Scope
2. Function Scope
3. Block Scope
1. Global Scope
Variables declared outside any function or block are in the global scope. These variables are
accessible from anywhere in the code.
<script>
var globalVar = "I am global";
let globalLet = "I am also global";
const globalConst = "I am a global constant";
function checkGlobal() {
console.log(globalVar); // I am global
console.log(globalLet); // I am also global
console.log(globalConst); // I am a global constant
}
checkGlobal();
console.log(globalVar); // I am global
console.log(globalLet); // I am also global
console.log(globalConst); // I am a global constant
</script>
2. Function Scope
Variables declared within a function using `var` are scoped to that function. These variables are
not accessible outside the function.
<script>
function localScope() {
var localVar = "I am local";
console.log(localVar); // I am local
}
localScope();
console.log(localVar); // ReferenceError: localVar is not defined
</script>
3. Block Scope
Variables declared with `let` or `const` within a block `{}` are scoped to that block. This means
they cannot be accessed from outside the block.
<script>
if (true) {
let blockScopedLet = "I am block scoped";
const blockScopedConst = "I am also block scoped";
console.log(blockScopedLet); // I am block scoped
console.log(blockScopedConst); // I am also block scoped
}