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

151
Views
How to execute this result within a limited function

Questions are as follows:
The first time you call the add, it will return 1;
the second time you call, it returns 2;
Can only be written in function

var add = function () {
     // start only 
    
     // end 
};
 
console.log(add()); // 1
console.log(add()); // 2

The current idea is that a global variable is needed
So the current way of writing
But this way of writing does not meet the requirements

var add = (function () {
 let counter=0
   return function () {
  counter += 1; return counter;}
}();

I don't know how to adjust the code to solve this question thank you

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

0

somethig like this?

var add = {
    time: 0,
    call: () => {
        add.time++;
        console.log(add.time);
    }
};

add.call(); // 1
add.call(); // 2

about 4 years ago · Juan Pablo Isaza Report

0

I'd do it like this. It implicitely creates a global variable, which is dirty as hell, but it meets the (strange) requirements.

var add = function () {
     if(typeof a === "undefined") a = 0;
     return ++a;
};
 
console.log(add()); // 1
console.log(add()); // 2

about 4 years ago · Juan Pablo Isaza Report

0

All the solutions that came to mind:

Use a property assigned to the function

// in JS, a function is also an object; you can assign properties to it.
function add() {
  if (add.value === undefined) add.value = 0;
  return ++add.value;
}

console.log(add());
console.log(add());

Create a local scope

var add = (function() {
  var value = 0;
  return function() {
    return ++value;
  };
})();

console.log(add());
console.log(add());

Use the global scope

function add() {
  if (window._currentValue === undefined) window._currentValue = 0;
  return ++window._currentValue;
}

console.log(add());
console.log(add());

I think that the first solution may be of particular interest to you.

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!