Sunday, August 25, 2024

JavaScript, Scopes Explained

JavaScript Scopes Explained
A function can have several scopes in JavaScript. Explain by example.
Answer: In JavaScript, the scope of a variable or function defines where it is accessible in your code. There are several types of scopes:
1. Global Scope: Variables or functions declared outside of any function or block have global scope. They can be accessed from anywhere in the codebase.

// Global scope
var globalVariable = 'I am global';
function globalFunction() {
console.log('Global function called');
}

Here, 'globalVariable' and 'globalFunction' are accessible throughout your JavaScript code.
2. Local Scope (Function Scope): Variables declared within a function have local scope. They are only accessible within that function.

function localScopeExample() {
var localVariable = 'I am local';
console.log(localVariable);
}
localScopeExample(); // Outputs: "I am local"
console.log(localVariable); // Throws an error: localVariable is not defined

In this example, 'localVariable' is scoped to the 'localScopeExample' function and cannot be accessed outside of it.
3. Block Scope (Introduced with 'let' and 'const'): Variables declared with 'let' and 'const' have block scope, which means they are only accessible within the block (typically denoted by curly braces '{}') where they are defined.

if (true) {
let blockScopedVariable = 'I am block scoped';
console.log(blockScopedVariable); // Outputs: "I am block scoped"
}
console.log(blockScopedVariable); // Throws an error: blockScopedVariable is not defined

Here, 'blockScopedVariable' is scoped to the 'if' block and cannot be accessed outside of it.
4. Lexical Scope (Closure): Functions in JavaScript create closures. This means that they retain access to variables in their lexical scope (the scope where they are defined), even when called outside of that lexical scope.

function outerFunction() {
var outerVariable = 'I am outer';
function innerFunction() {
console.log(outerVariable);
}
return innerFunction;
}
var closure = outerFunction();
closure(); // Outputs: "I am outer"

In this example, 'innerFunction' retains access to 'outerVariable' even after 'outerFunction' has finished executing, due to lexical scoping.
Understanding these scopes is crucial for writing efficient and bug-free JavaScript code, especially when dealing with variables and functions that need to maintain certain levels of accessibility and privacy within your application.

No comments:

Post a Comment

Hot Topics