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

225
Views
How can I pass this function to another function to use the iterator of the top function?

So I wanted to replicate the ๐จ function/operation in Javascript.

For the people not familiar with it, here is an example:

Capital sigma

The above displayed operation would translate to Javascript code like this:

var sum = 0;
for (var n = 1; n <= 10; n++) {
    sum += n ** 2;
}

Now I wanted to wrap it as a function, where the operation that each iteration should do would be passed as a function. So the example above would be passed like this:

๐จ(1, 10, n => n ** 2)
function ๐จ(start, end, func) {
    var sum = 0;
    for (var i = start; i <= end; i++) {
        sum += func();
    }
    return sum;
}

However, the above example returns NaN because the variable passed doesn't use the iterator of the for-loop. Is there a way to do that?

about 4 years ago ยท Juan Pablo Isaza
2 answers
Answer question

0

You're not passing in the iterative value to the callback func:

    for (var i = start; i <= end; i++) {
        sum += func(i); // you have to pass it in so func knows how to func
    }
about 4 years ago ยท Juan Pablo Isaza Report

0

But why do we want func()? This works fine too I guess. It outputs the same answer 385.

function ๐จ(start, end){
  let sum = 0;
for (let n = start; n <= end; n++) {
    sum += n ** 2;
}
return sum;
}
alert(๐จ(1, 10));

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!