DeveloperBreeze

Javascript Programming Tutorials, Guides & Best Practices

Explore 93+ expertly crafted javascript tutorials, components, and code examples. Stay productive and build faster with proven implementation strategies and design patterns from DeveloperBreeze.

Understanding Closures in JavaScript: A Comprehensive Guide

Tutorial August 30, 2024
javascript

function greeting(message) {
    return function(name) {
        console.log(`${message}, ${name}!`);
    };
}

const sayHello = greeting("Hello");
sayHello("Alice");  // Output: "Hello, Alice!"
sayHello("Bob");    // Output: "Hello, Bob!"

const sayGoodbye = greeting("Goodbye");
sayGoodbye("Alice");  // Output: "Goodbye, Alice!"

Here, the greeting function creates a closure that remembers the message variable. This allows the inner function to use message whenever it is called.