PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, December 13, 2022

[FIXED] What is this syntax in NodeJS?

 December 13, 2022     node.js, syntax     No comments   

Issue

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?


Solution

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.



Answered By - Manish Gharat
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing