Make a variable not reseateable

1

When you called a function and it has variables declared inside and you call the function again, as for example in a recursive function, the variables inside are declared again, and my problem is,

How can I make a variable NOT restart? , by this I mean that you do not lose your last value when you call the same function again.

Example:

function callMe(n){
 var arr = [];
 if(arr.length < 4) {
 arr.push(n);
 callMe(n*2);
 }
 else {
 return 0;
 }
}

console.log(callMe(2));

Since the variable arr is always redefined, an infinite loop is caused.

I know it can be done by passing the array as a parameter, but that is not the focus of my question, but how to make a variable not lose its last value.

    
asked by Eduardo Sebastian 17.11.2017 в 14:48
source

2 answers

3

One option is to create an object:

var obj={
  arr: [],
  callMe: function (n) {
    if(this.arr.length < 4) {
      this.arr.push(n);
      this.callMe(n*2);
    } else {
      return 0;
    }
  }
}

obj.callMe(2);
console.log(obj.arr);

But in the case of recursive functions, the ideal is that you pass the variable as a parameter, returning it as a result:

//La segunda variable es opcional, si no la pasamos se asume un array vacío
function callMe(n,arr=[]) {

  if(arr.length < 4) {
      arr.push(n);
      //caso recursivo, devolvemos el resultado de la llamada
      return callMe(n*2,arr); 
  } else {
      return arr; //caso base, el array tiene ya 4 elementos
  }
}
  
  console.log(callMe(2));
    
answered by 17.11.2017 / 15:13
source
4

You must declare the variable arr outside the scope of the function.

Here is an example. The function that is executed is the internal anonymous function that returns when executing the first one that serves to define a scope for the variable and the function that will use it:

var callMe = function(){
  var arr = [];
  return function(n){
    if (arr.length < 4){
      arr.push(n);
      callMe(n*2);
      return arr;
    }
    else{
      return 0;
    }
  };
}();


console.log(callMe(2));
    
answered by 17.11.2017 в 15:00