Skip to content

JavaScript closures | Basic code

  • by

JavaScript closure gives you access to an outer function’s scope from an inner function. Closures are frequently used in JavaScript for object data privacy, in event handlers and callback functions, and in partial applications, currying, and other functional programming patterns.

function init() {
  var name = 'Mozilla'; // name is a local variable created by init
  function displayName() { // displayName() is the inner function, a closure
    alert(name); // use variable declared in the parent function
  }
  displayName();
}
init();

Source: developer.mozilla.org

JavaScript closures example

Simple example code access to the outer scope of a function from inside the inner function, even after the outer function has closed.

<!DOCTYPE html>
<html>
<body>
  <script>    
   function hello() {

    // variable defined in inner function
    let name = 'John';

    // inner function
    function displayName() {

        // accessing name variable
        return 'Hi' + ' ' + name;
        
      }
      return displayName;
    }
    const h = hello();
    console.log(h); // returns the function definition
    console.log(h()); // returns the value
  </script>  

</body>
</html>

Output:

JavaScript closures

More example

function greeting(message) {
   return function(name){
        return message + ' ' + name;
   }
}
let sayHi = greeting('Hi');
let sayHello = greeting('Hello');

console.log(sayHi('John')); // Hi John
console.log(sayHello('John')); // Hello John

Closures are often used to create private variables and functions in JavaScript, by defining them inside a function and returning them as a closure. This way, the private variables and functions can only be accessed by the returned closure, and not by any other code outside the function.

Comment if you have any doubts or suggestions on this JS function topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *