Closure in JavaScript

The closure is an important concept in functional programming. Closure means that an inner function always has access to the vars and lets of outer function, even after the function has returned. It is a form of lexical scoping.

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). Before getting into closure, we need to know the following terms:

Scope:

A scope is created by a function or a code block. While defining a variable, we want to create some boundaries for variables. The accessibility of variables is within these boundaries (i.e) scope. Outside scope, the variable is inaccessible.

Example:
function f1(){
  //function scope
  let a = 2;
  console.log(a);
}
f1();
console.log(a); // outside scope Reference error
Output:

2

Reference error

When variable a is accessed within its function f1 it gets executed and returns 2. But when we try to access outside function it throws reference error.

Scope is a policy that rules the accessibility of variables.

Lexical Scope:

Lexical scope defines the scope of a variable by position of the variable declared in source code. Outer scope determined statically or at lexical time.

According to lexical scoping, the scopes can be nested and inner function can access variables declared outside.

Example:
let a = 2; // global variable
function f1(){
  let b = 3; // local variable
  console.log(a+b);
}
f1();
Output:

5

Now going to closure,

As we already know, closure means that an inner function always has access to the vars and parameters of its outer function, even after returned.

Example:

function f1(){

  //outer function

  let a=2;

  function f2(){

    //inner function

    console.log(a);

  }

  f2();

}

f1();

Output:

2

Now inner function can access outer variable even if it is executed separately.

function f1(){
  //outer function
  let a=2;
  function f2(){
    //inner function
    console.log(a);
  return f2();
}
var f3 = f1(); // function expression
f3;
Output:

2

Functions are first-class citizens in JavaScript. A function can return another function in JavaScript. A function which is assigned to a variable is called function expression.

Another important feature of closure is that outer variable keeps their state between multiple calls. But inner function does not keep separate copy of outer variable instead reference outer variable.

That means value of outer variable is changed if you change inner variable.

Example:

function f1(){

  //outer function

  var a=2;

  function f2(){

    //inner function

    return a+1;

  }

  return f2();

}

var f3 = f1(); // function expression

f3;

Output:

3

Closure is a function that access its lexical scope even executed outside of its lexical scope.

When to use closure?

Closure is an important concept in functional programming. Currying in functional programming is possible because of closure.

Currying is a process that allows you to transform a function with multiple arguments into a sequence of nesting functions. Instead of a function taking all arguments at one time, it takes the first one and returns a new function, which takes a second one and returns another function and so on.

Currying transforms f(a,b,c) into f(a) (b) (c).

Example:
function add(a) {

  return function executeadd(b) {

    return a + b;

  }

}

const sum = add(2);

sum(3);

sum(5);

const sum1 = add(3);

sum(4);
Output:

6

We will see about closure in loop in next part.

Higher Order Functions and decorators in Python

Higher Order Functions:

Higher Order Functions (HOFs) are functions that express complex concepts by combining simpler functions into a new function. It is a function that contains a function as parameter and returns another function as a result.

Properties of Higher Order Functions:

  1. We can store a function inside a variable.
  2. A function can act as instance of an object
  3. We can pass a function as an argument to another function
  4. We can store Python higher order functions in data structures such as list, hash tables etc.,

Functions as object:

               In Python, a function can be assigned to a variable. Here, a reference to the function is created.

Example:

Passing Function as an argument to another function:

Functions are like objects in Python, so they can be passed as an argument to another function.

Returning Function:

As functions are objects, we can also return a function from another function.

Decorators as Higher Order Function:

               We can use decorators as higher order function. Decorators in Python allow us to extend behavior of methods or functions without explicitly modifying it.

Decorators allow us to wrap another function to extend the behavior of wrapped function, without modifying it.

Syntax:

# Using a decorator  

@myDecorator  

def Python_Decorator():   

.

.

The above decorator syntax is equivalent to the below syntax for using decorator as higher order function in python.

def Python_Decorator():   

    .  

    .  

Python_Decorator = @myDecorator(Python_Decorator)  

Example:

In the next article we will see about map(), reduce() and filter() higher order functions.