Computer >> Computer tutorials >  >> Programming >> Javascript

What are JavaScript Function Closures?


JavaScript function closure is the grouping of a function and where that function was declared. In JavaScript, all functions work like closures. A closure is a function uses the scope in which it was declared when invoked. It is not the scope in which it was invoked.

Here’s an example

Live Demo

<!DOCTYPEhtml>
<html>
   <body>
      <h2>Working with JavaScript Closures</h2>
      <script>
         var num = 10;
         function a() {
            var num = 15;
            b(function() {
               alert(num);
            });
         }
         function b(f) {
            var num = 30;
            f();
         }
         a();
      </script>
   </body>
</html>