Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

322
Views
How to call a function Multiple times

Here is the code snippets

let sum = a => b => b ? sum(a + b) : a;
console.log(sum(10)(20)(3)(4)());

So we are calling the sum function 5 times But let's assume we have an array of any length which contains only numbers

let arrayValue = [1,2,3,4,5,...];

now I want to call the sum function to the length of that array where the last call should be () as it does not contain any number;

Desired Output should be sum(1)(2)(3)(4)(5)() and this will generate programmatically depending on the length of the array

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

If you look at

console.log(sum(10)(20)(3)(4)());

It's basically doing this:

const x1 = sum(10);
const x2 = x1(20);
const x3 = x2(3);
const x4 = x3(4);
const x5 = x4();
console.log(x5);

So the question is: How do we do that from this starting point?

let arrayValue = [1,2,3,4,5];

The answer is either a loop or recursion. A loop is simple enough, so let's do that:

let x = sum;
for (const value of arrayValue) {
    x = x(value);
}
x = x();
console.log(x);

let sum = a => b => b ? sum(a + b) : a;

function example(arrayValue) {
    let x = sum;
    for (const value of arrayValue) {
        x = x(value);
    }
    x = x();
    console.log(arrayValue.join(", "), "=>", x);
}

example([10, 20, 3, 4]);
example([1, 2, 3, 4, 5]);

We start by setting x to sum (the function, not a call to it), then for each array value we call whatever function x currently refers to passing in the value and storing the return value back in x again. When we run out of values, we call the result with no argument.

about 4 years ago · Juan Pablo Isaza Report

0

You can loop over to the length of the array. You can use .length property to do this and then call your function inside the loop.

Example:

let arrayValue = [1, 2, 3, 4, 5 , …];

for (let i = 0; i < arrayValue.length; i++) {
  someFunction(arrayValue[i]);
}

Reference : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length

I hope this is what you are looking for.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!