Scope in JavaScript refers to the visibility and accessibility of variables, functions, and objects in different parts of your code. JavaScript has three main types of scope:
- Global scope
- Function scope
- Block scope (introduced in ES6 with let and const)
Here's an example demonstrating these scopes:
// Global scope
let globalVar = "I'm global";
function exampleFunction() {
// Function scope
let functionVar = "I'm function-scoped";
if (true) {
// Block scope
let blockVar = "I'm block-scoped";
var functionScopedVar = "I'm function-scoped too";
console.log(globalVar); // Accessible
console.log(functionVar); // Accessible
console.log(blockVar); // Accessible
console.log(functionScopedVar); // Accessible
}
console.log(globalVar); // Accessible
console.log(functionVar); // Accessible
console.log(functionScopedVar); // Accessible
// console.log(blockVar); // Error: blockVar is not defined
}
exampleFunction();
console.log(globalVar); // Accessible
// console.log(functionVar); // Error: functionVar is not defined
// console.log(blockVar); // Error: blockVar is not defined
// console.log(functionScopedVar); // Error: functionScopedVar is not defined
Top comments (0)