JavaScript closures vs. anonymous functions


Anonymous Functions

Anonymous, as the name suggests, allows creating a function without any names identifier. It can be used as an argument to other functions. They are called using the variable name:

This is how JavaScript anonymous functions can be used:

var func = function() {
   alert(‘This is anonymous');
}
func();

Another example can be the following:

setTimeout(function() {
   alert('Demo');
}, 3000);

JavaScript Closures

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

Here’s an example:

<!DOCTYPE html>
<html>
   <body>
      <h2>JavaScript Closures</h2>
      <script>
         var p = 20;
         function a() {
            var p = 40;
            b(function() {
               alert(p);
            });
         }
         function b(f) {
            var p = 60;
            f();
         }
         a();
      </script>
   </body>
</html>

Updated on: 12-Sep-2019

393 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements