Function bundled along with it’s lexical scope is closure.
function x() {
var a = 7;
function y() {
console.log(a);
}
return y;
}
var z = x();
console.log(z); // value of z is entire code of function y.
function z() {
var b = 900;
function x() {
var a=7;
function y(){
console.log(a,b);
}
y();
}
x();
}
z(); // 7 900
Advantages of Closure:
Certainly! Let’s explore examples for each of the advantages you’ve mentioned:
Example: Suppose we’re building a web application, and we want
to create a module for handling user authentication. We can
create a auth.js
module that exports functions like login
,
logout
, and getUserInfo
.
// auth.js
const authModule = (function () {
let loggedInUser = null;
function login(username, password) {
// Authenticate user logic...
loggedInUser = username;
}
function logout() {
loggedInUser = null;
}
function getUserInfo() {
return loggedInUser;
}
return {
login,
logout,
getUserInfo,
};
})();
// Usage
authModule.login('john_doe', 'secret');
console.log(authModule.getUserInfo()); // 'john_doe'
Example: Let’s create a curried function to calculate the total price of items with tax.
const calculateTotalPrice = (taxRate) => (price) => price + price * (taxRate / 100);
const calculateSalesTax = calculateTotalPrice(8); // 8% sales tax
const totalPrice = calculateSalesTax(100); // Price with tax
console.log(totalPrice); // 108
Example: Implement a memoized Fibonacci function.
function fibonacci(n, memo = {}) {
if (n in memo) return memo[n];
if (n <= 1) return n;
memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo);
return memo[n];
}
console.log(fibonacci(10)); // 55
Example: Create a Person
class with private properties.
class Person {
#name; // Private field
constructor(name) {
this.#name = name;
}
getName() {
return this.#name;
}
}
const person = new Person('Alice');
console.log(person.getName()); // 'Alice'
// console.log(person.#name); // Error: Private field '#name' must be declared in an enclosing class
setTimeout
allows scheduling a function to run after a
specified delay. It’s commonly used for asynchronous tasks,
animations, and event handling.Example: Delayed message display.
function showMessage(message, delay) {
setTimeout(() => {
console.log(message);
}, delay);
}
showMessage('Hello, world!', 2000); // Display after 2 seconds
These examples demonstrate the power and versatility of closures in JavaScript! 🚀
Disadvantages of Closure:
Watch Live On Youtube below: