-1

I am learning NodeJS, coming from other languages (C#, etc) and I find some of the syntax to be confusing.

For example this piece of code:

 for(var index in files) {
    console.log("-->"+index);
    var task = (function(file) { 
      return function() {
        fs.readFile(file, function(err, text) {
          if (err) throw err;
          countWordsInText(text);
          checkIfComplete();
        });
      }
    })(filesDir + '/' + files[index]);
    tasks.push(task); 
  }

What is this? var task= (function(file){return function(){......}})(filesDir+.....);

There is a function that is calling a function and suddenly some parameters outside?

I am guessing it is defining a list of functions but what is the rule for this syntax?

halfer
  • 19,824
  • 17
  • 99
  • 186
KansaiRobot
  • 7,564
  • 11
  • 71
  • 150
  • Possible duplicate of [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – CertainPerformance Nov 12 '18 at 10:31
  • It's an IIFE, but an unnecessarily confusing one - just use `const` instead of `var` and you avoid the need for it – CertainPerformance Nov 12 '18 at 10:31
  • [Immediately-invoked function expression](https://en.wikipedia.org/wiki/Immediately-invoked_function_expression), and albeit one that returns a function itself. Does nobody do computing science anymore? – Neil Lunn Nov 12 '18 at 10:32
  • thanks! Apparently this is not CS but a "JavaScript programming language idiom" (wikipedia). Excellent link. – KansaiRobot Nov 12 '18 at 10:35

2 Answers2

1

It's called IIFE (Immediately Invoked Function Expression). Basically, you define a function

function (){}

and immediately execute it

(function(){})();

What the code you've posted is doing is, executing a function and storing the returned value in task.

halfer
  • 19,824
  • 17
  • 99
  • 186
Manish Gharat
  • 400
  • 1
  • 10
1

Thats an IIFE (Immediately Invoked Function Expression). Basically it's a JavaScript function that runs as soon as it is defined.

(function () {
    statements
})();

Taken right from mozi//a: - It is a design pattern which is also known as a Self-Executing Anonymous Function and contains two major parts. The first is the anonymous function with lexical scope enclosed within the Grouping Operator (). This prevents accessing variables within the IIFE idiom as well as polluting the global scope.

The second part creates the immediately executing function expression () through which the JavaScript engine will directly interpret the function.

Nelson Owalo
  • 2,324
  • 18
  • 37