How do JavaScript closures work?

JavascriptWeb DevelopmentFront End Technology

In JavaScript, closure is the grouping of a function and where that function 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.

Example

You can try to run the following code to learn how to work with JavaScript closures:

<!DOCTYPE html>
<html>
   <body>
      <h2>Working with JavaScript Closures</h2>
      <script>
         var p = 10;
         function a() {
            var p = 15;
            b(function() {
               alert(p);
            });
         }
         function b(f){
            var p = 30;
            f();
         }
         a();
      </script>
   </body>
</html>
raja
Published on 09-Jan-2018 09:03:12
Advertisements