This page looks best with JavaScript enabled

Repeated function calls using an abstract pattern in Javascript

 ·   ·  ☕ 1 min read

Use this if you want to repeatedly call a function for known arguments, or in case you just need a IIFE.

If you want a repeatedly called functions, you would typically -

  1. Call function in a loop
  2. Use recursion

For e.g. -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function printStr(str) {
  console.log(str);
}

printStr("hello");
printStr("people");

/*
hello
people 
*/

You can do it in a more concise way like so -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
(function(str) {
  console.log(str);
  return arguments.callee;
  // return function for next call
})("hello")("world")("and")("people");

/*
hello
world
and
people
*/

Note that you are not returning a string, but a whole function and calling that function for the given arguments. In the statement, we use arguments to call the function that returns a function, and invoke the returned function on a specific argument thereon.

You may remember arguments from our discussion on arguments object in Javascript and practical application from our curry functions in Javascript post.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things