Javascript printing different elements for push and unshift

Hi,

I was practicing a few personal challenges for basic javascript and wrote the following code:

/*code to print an array of multiples using recursive functions only and not using loops. */

var x = [];

function mNumbers(n) {
  if (n < 1) {
      return 1;
  } else {
      n = parseInt(n) * parseInt(mNumbers(n-1));
      x.unshift(n);
  }
  return x;
}

When I call mNumbers(5), it returns: [120, 24, 6, 2, 1]

But, if I replace x.unshift(n); code with x.push(n); and call mNumbers(5), it is returning [1, 2, 3, 4, 5]

I am confused what I am doing wrong here, I was expecting the result to be: [1,2,4,6,24,120]. Can someone please help.

Your issue is that parseInt() will take your array, the array returned by the function, stringify it to a comma separated list, and then take only the first number, so you get each number multiplied by 1 when you have push as that is the first item in the array, or by last added item when using unshift. It is not really a good way in my opinion to get a number from an array.


You may also want to keep this in consideration:

Your code contains global variables that are changed each time the function is run. This means that after each function call completes, subsequent function calls start with the previous value. To fix this, make sure your function doesn’t change any global variables, and declare/assign variables within the function if they need to be changed.

Example:

var myGlobal = [1];
function returnGlobal(arg) {
  myGlobal.push(arg);
  return myGlobal;
} // unreliable - array gets longer each time the function is run

function returnLocal(arg) {
  var myLocal = [1];
  myLocal.push(arg);
  return myLocal;
} // reliable - always returns an array of length 2
1 Like

This is very helpful, thanks for the clarification @ilenia!