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

180
Views
Add values on subsequent call in javascript function.?

Let's consider I have the following function call,

function add(){
    x = 0 ;
    for(i = 0 i < ##; i++){ // need to run a loop four times
    x+=1
    }
}

Let's consider I am trying to Implement the function that will add one on each subsequent call, like below

console.log(add()()().getValue()); // 3
console.log(add().getValue()); // 1
console.log(add()().getValue()); // 2
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

A call to add must return a function which also has a getValue method, and each call to that function must return the same thing. So:

function add() {
    var x = 1;
    
    function inner() {
        x += 1;
        return inner;
    }
    
    inner.getValue = function () {
        return x;
    }
    
    return inner;
}

console.log(add()()().getValue()); // 3
console.log(add().getValue()); // 1
console.log(add()().getValue()); // 2

about 4 years ago · Juan Pablo Isaza Report

0

My guess is they were expecting you to use toString() which is not the greatest way of doing this.

function add(x = 0) {
  function next() {
    return add(x+1);
  }
  next.toString = function () {
    return x;
  };
  return next;
}

console.log("example 1", add()()()());
console.log("example 2", add()()()()()()()()());

about 4 years ago · Juan Pablo Isaza Report

0

I think you are trying to emulate the behavior of generator functions. Here is a snippet that illustrates one way you could do it with a generator.

function* adder() {
  let x = 0;
  while (true) {
    yield x + 1;
    x++;
  }
}

const add = adder();

const firstValue = add.next();

const secondValue = add.next();

const thirdValue = add.next().value;
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!