Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are closures higher order functions?

Higher order function is defined as:

A function that takes a function as an argument and/or returns a functions as return value.

Closure example:

function outer() {
  const name = 'bob';

  function inner(lastName) {
    console.log('bob' + lastName);
  }

  return inner;
}

Do closures like the one defined above fit in to this category? It seems like they return a function as a return value, right?

like image 547
user117829 Avatar asked Dec 22 '18 22:12

user117829


2 Answers

A closure gives access to an outer function’s scope from an inner function. Closures are commonly used to give objects data privacy.

A Higher-Order function is a function that receives a function as an argument or returns the function as output.

//This function is a higher order function
function higherOrderFunction(f, ...outerArgs) {
    return function (...innerArgs) { 
        // It has access to outer args. So we can say this function has a closure over the scope of outer function
        let args = [...outerArgs, ...innerArgs];
        return f.apply(this, args);
    };
}

const f = function (x, y, z) { return x * y * z };

higherOrderFunction(f, 1)(1, 3) // => (1*2*3);
like image 36
Debashish Hota Avatar answered Sep 20 '22 02:09

Debashish Hota


A closure does not mean that it necessarily is returned by a function. In JavaScript every function actually is a closure. A closure generally is a function that has access to the declaration context's scope.

function outer(lastName)
{
  const name = 'Bob';

  function inner(lastName)
  {
    // here we have access to the outer function's scope
    // thus it IS a closure regardless whether we return the function or not
    console.log(name + ' ' + lastName);
  }
  
  inner(lastName);
}

outer('Marley');

To be more concrete: A closure is actually a concept of binding a current scope to a subcontext. We frequently shortly say 'closure' to a function that gets such a mapped context. Declaration context does not mean declaration time, much more the declaration context in its active state at its call time. This behaviour is used to bind a context to an inner function and return the function with the bound context:

function outer(lastName)
{
  // this is the declaration context of inner().
  
  const name = 'Bob';

  function inner()
  {
    // here we have access to the outer function's scope at its CALL time (of outer)
    // this includes the constand as well as the argument
    console.log(name + ' ' + lastName);
  }
  
  return inner;
}

var inner1 = outer('Marley');
var inner2 = outer('Miller');

function output()
{
  // this is the caller context, the const name ist NOT used
  const name = 'Antony';
  inner1(); // outputs 'Bob Marley'
  inner2(); // outputs 'Bob Miller'
}

// test the output
output();
like image 67
Quasimodo's clone Avatar answered Sep 23 '22 02:09

Quasimodo's clone