Scope in JavaScript refers to the accessibility of variables, functions, and objects in certain parts of your code. It determines where variables and functions can be accessed or referenced.
Variables declared outside of any function or block are in the global scope. Accessible from anywhere in the code.
let globalVar = "I am global";
function showGlobalVar() {
console.log(globalVar); // Accessible here
}
showGlobalVar();
console.log(globalVar); // Accessible here too
Variables declared inside a function are in the function scope. Accessible only within the function where they are declared.
function myFunction() {
let functionScopedVar = "I am inside a function";
console.log(functionScopedVar); // Accessible here
}
myFunction();
// console.log(functionScopedVar); // Error: Not accessible here
Variables declared with let
or const
inside a block {}
are in block scope.
Accessible only within the block where they are defined.
{
let blockScopedVar = "I am inside a block";
console.log(blockScopedVar); // Accessible here
}
// console.log(blockScopedVar); // Error: Not accessible here
Inner functions can access variables of their parent functions due to lexical scoping.
function outerFunction() {
let outerVar = "I am outer";
function innerFunction() {
console.log(outerVar); // Accessible due to lexical scoping
}
innerFunction();
}
outerFunction();
Variables defined in a module are scoped to that module and are not accessible globally.
Modules use the import
and export
keywords.
// In module.js
export let moduleScopedVar = "I am in a module";
// In main.js
import { moduleScopedVar } from './module.js';
console.log(moduleScopedVar);