Skip to content
Advertisement

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

Advertisement

Answer

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.

6 People found this is helpful
Advertisement