Functions in Depth
Scope and Closures in JavaScript
Scope
Scope refers to the region in your code where a variable is declared and can be accessed. JavaScript has two types of scope: global scope and local (or function) scope.
Example:
// Global scope
let globalVar = 'I am global';
function exampleFunction() {
// Local scope
let localVar = 'I am local';
console.log(globalVar); // Accessible
}
console.log(globalVar); // Accessible
console.log(localVar); // Error - localVar is not defined outside the functionClosures
A closure is formed when a function is defined inside another function and has access to the outer function's variables. This allows the inner function to "close over" and retain access to the outer function's scope, even after the outer function has finished executing.
Example:
function outerFunction() {
let outerVar = 'I am outer';
function innerFunction() {
console.log(outerVar); // Accessing outerVar from the outer function's scope
}
return innerFunction;
}
let closure = outerFunction();
closure(); // Outputs: I am outerIn this example, innerFunction forms a closure over outerVar, allowing it to access outerVar even after outerFunction has completed execution.
Higher-Order Functions and Callbacks
Higher-Order Functions
A higher-order function is a function that takes one or more functions as arguments or returns a function as a result. This concept allows for the composition of functions, enhancing modularity and reusability.
Example:
// Higher-order function
function multiplier(factor) {
return function (number) {
return number * factor;
};
}
let double = multiplier(2);
let triple = multiplier(3);
console.log(double(5)); // Outputs: 10
console.log(triple(5)); // Outputs: 15In this example, multiplier is a higher-order function that returns a new function. This new function (double and triple) can then be used to multiply numbers by a specific factor.
Callbacks
A callback is a function passed as an argument to another function, to be executed later. Callbacks are often used in asynchronous operations, event handling, and higher-order functions.
Example:
// Higher-order function with a callback
function doSomethingAsync(callback) {
setTimeout(function () {
console.log('Operation completed');
callback();
}, 1000);
}
// Callback function
function afterCallback() {
console.log('Callback executed');
}
// Using the higher-order function with a callback
doSomethingAsync(afterCallback);In this example, doSomethingAsync is a higher-order function that takes a callback function (afterCallback). The callback is executed after the asynchronous operation (a simulated timeout) is completed.
Understanding scope, closures, higher-order functions, and callbacks is crucial for writing effective and modular JavaScript code. These concepts are foundational for more advanced JavaScript programming and play a significant role in building scalable and maintainable applications.