Scope of a variable means accessible of a particular variable within the program.
There are three variable scopes in JavaScript which are as follows:
Variables declared inside a function have local scope and can only be accessed within that function
function localScope(){
var localVariable = "Local Value";
console.log(localVariable); // Accessing local variable
}
console.log(localVariable); // variable not accessible
localScope(); // Outputs: "Local Value"
Variables declared using var have function scope, meaning they are only accessible within the function where they are defined.
function functionScope(){
if (true) {
var functionVariable = "Value";
console.log(functionVariable); // Accessing function-scoped variable
}
console.log(functionVariable); // Accessible here as well
}
console.log(functionVariable); // Variable not accessible
functionScope();
Global scope refers to the outermost scope where variables are declared outside of any function or block.
var globalVariable = "Global scope";
function globalFunction() {
console.log(globalVariable); // Accessing global variable within a function
}
globalFunction(); // Outputs: "Global scope"
console.log(globalVariable); // Outputs: "Global scope"
It's important to understand scope in JavaScript, as it can impact variable accessibility and prevent unintended variable conflicts. Additionally, the introduction of let and const in ES6 has provided developers with better control over block-level scoping.