K
K
Keardo2014-11-29 21:49:20
JavaScript
Keardo, 2014-11-29 21:49:20

How to understand closures in Javascript?

The article about higher-order functions on habrahabr.ru/post/241155 has the following code:

function noisy(f) {
  return function(arg) {
    console.log("calling with", arg);
    var val = f(arg);
    console.log(f);
    console.log("called with", arg, "- got", val);
    return val;
  };
}
noisy(Boolean)(0);

I just don't understand this line: var val = f(arg);
After all, f is not defined anywhere as a function, it is only passed to the higher function as a variable, why did it turn out to be a function?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Ali Aliyev, 2014-11-29
@Keardo

closures
are very simple. the function f is passed as an argument to the noisy function. this is done for callbacks. simple example:

var name = function(f) {
  alert(f());
}

name(function() {
    return 100;
});

further function returns a function:
var name = function() {
  console.info('Parent function');
  return function() {
    console.info('Nested function');
  }
}

name()();
// должно вывести
// Parent function
// Nested function

I
Ivan Solomennikov, 2014-11-29
@ivsol

Javascript Jedi #15 - Closures

E
Elizaveta Borisova, 2014-11-29
@Elizaveta

Probably because we are talking about functional programming. It says below that the function is not entirely convenient.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question