-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?

4

2 Answers 2

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.

0
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.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.