0

I recently found JavaScript code like this:

someFunction()()

Function immediately invoked right after function without classic IIFE syntax.

What is that kind of syntax called? And how it works?

Avinash
  • 1,245
  • 11
  • 19
enk1
  • 527
  • 3
  • 7

2 Answers2

5

Its a function that returns another function.

Here is an example on how it works, this can help you to understand better.

function sum(x){
  return function(y){
    return x+y;
  }
}
sum(3)(5); //8
Avinash
  • 1,245
  • 11
  • 19
1

For you code to work:

someFunction()();

You need to have code that looks like this:

function someFunction() {
  console.log('someFunction()');
  // do something before return
  return function() {
    console.log('someFunction()()');
    // do something else here
  }
}

someFunction()();
    

In this example you first call someFunction then you call the function that was returned by someFunction.

This can be good to do when you need to pass in a variable that will be used in the inner function but the inner function will be called in the future like this:

function someFunction(outerVal) {
  console.log('Outer called.');
  return function(innerVal) {
    console.log('inner called.');
    return outerVal * innerVal;
  }
}

var inner = someFunction(12);

setTimeout(()=> {
  console.log(inner(4));
}, 1000);

I use this often in Node.js for common middle-ware that needs a single value to be unique.

app.get('/dogs', myFn('woof'));
app.get('/cats', myFn('meow'));
app.get('/birds', myFn('tweet'));

function myFn(word) {
  return function(req, res, next) {
    res.write(word).end();
  }
}

That is an over simplification, but can be vary powerful.

Intervalia
  • 10,248
  • 2
  • 30
  • 60