Scope in JavaScript defines the accessibility of variables and functions within different parts of the code. It determines where a variable or function can be accessed or modified.
Global Scope:
Variables declared outside of any functions or blocks have a global scope, making them accessible from anywhere in the code.
Example:
const globalVar = "I am global";
function exampleFunction() {
console.log(globalVar); // Accessible here
}
console.log(globalVar); // Accessible here too
File or Module Scope:
In modular JavaScript, variables declared at the top level of a file (module) have a scope limited to that file, making them accessible only within that file.
Example:
// module.js
const moduleVar = "I belong to this module";
// main.js
console.log(moduleVar); // Will result in an error, moduleVar is not defined here
Function Scope:
Variables declared inside a function are limited to that function's scope, making them accessible only within the function.
Example:
function exampleFunction() {
const functionVar = "I'm scoped within this function";
console.log(functionVar); // Accessible here
}
console.log(functionVar); // Will result in an error, functionVar is not defined here
Code Block Scope:
JavaScript introduced block-scoped variables with 'let' and 'const', which are limited to the scope of a code block.
Example:
if (true) {
let blockVar = "I'm scoped within this block";
console.log(blockVar); // Accessible here
}
console.log(blockVar); // Will result in an error, blockVar is not defined here
Block Scoped Variables:
Using 'let' and 'const', variables can be declared with block scope, making them accessible only within the block they're defined in.
Example:
{
let blockScopedVar = "I'm scoped within this block";
console.log(blockScopedVar); // Accessible here
}
console.log(blockScopedVar); // Will result in an error, blockScopedVar is not defined here
Global Variables:
Variables declared outside of blocks or functions have global scope, which means they're accessible throughout the program.
Example:
const globalVar = "I'm accessible everywhere";
function exampleFunction() {
console.log(globalVar); // Accessible here
}
console.log(globalVar); // Accessible here too