JavaScript closures vs. anonymous functions

JavascriptWeb DevelopmentFront End Technology

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');

Another example can be the following:

setTimeout(function() {
}, 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>
      <h2>JavaScript Closures</h2>
         var p = 20;
         function a() {
            var p = 40;
            b(function() {
         function b(f) {
            var p = 60;
Published on 09-Jan-2018 13:30:18