What is the scope of a variable in JavaScript?
Asked on Jul 06, 2024
Answer
In JavaScript, the scope of a variable determines where it can be accessed or referenced. Variables can have global scope, function scope, or block scope.
// Global scope
var globalVar = "I am global";
function testFunction() {
// Function scope
var functionVar = "I am local to the function";
if (true) {
// Block scope (ES6+)
let blockVar = "I am local to the block";
console.log(blockVar); // Accessible here
}
console.log(functionVar); // Accessible here
// console.log(blockVar); // Error: blockVar is not defined
}
console.log(globalVar); // Accessible here
// console.log(functionVar); // Error: functionVar is not defined
Additional Comment:
✅ Answered with JavaScript best practices.- Variables declared with "var" have function scope, meaning they are accessible within the function they are declared in.
- Variables declared with "let" and "const" have block scope, meaning they are accessible within the block they are declared in (e.g., inside a loop or conditional statement).
- Global variables are accessible from anywhere in the code after they are declared.
Recommended Links:
← Back to All Questions