Solution works but is not accepted

Can somebody help me? I managed to create a code that achieved the requested result, but the exercise does not accept it!

let newArray = []
const reverseArray = (oldArray) => {
  for (let i = oldArray.length -1; i>= 0; i--) {
    let changeIndex = oldArray[i];
    newArray.push(changeIndex);
  }
 return newArray;
}

Then uncommenting the last piece of code I get exactly this result:
[ ‘This’, ‘will’, ‘all’, ‘make’, ‘sense.’ ]
So why is this solution not accepted?

Being as it is outside of the function, it does not get reset on each call.

Thank you very much! Yeah I had an issue with the newArray variable, I needed to declare it outside of the loop otherwise its scope would have not let me call it outside of the loop function. So I thought about declaring it as a global variable to solve this issue.
So I realized now that I could declare it inside the function, but before the loop, and now the code is accepted!
Although I am not entirely sure why it doesn’t reset on each call? I tried to change the inputs of sentence and the results do indeed change even when it’s declared as a global variable.

1 Like

With the initialization outside of the function, each call will be building upon the same array the previous call(s) built upon. We are given access to the newArray by assigning the return value to a variable in caller scope.

a = [2, 4, 6, 8]
b = reverseArray(a)
console.log(b)
// [8, 6, 4, 2]

Consider,

const newArray = []
const reverseArray = (oldArray) => {
  for (let i = oldArray.length -1; i>= 0; i--) {
    let changeIndex = oldArray[i];
    newArray.push(changeIndex);
  }
 return newArray;
}
reverseArray([2, 4, 6, 8, 10])
console.log(newArray)    //  [ 10, 8, 6, 4, 2 ]
reverseArray([2, 4, 6, 8, 10])
console.log(newArray)    //  [ 10, 8, 6, 4, 2, 10, 8, 6, 4, 2 ]

Now consider this example where the array is initialized locally…

const reverseArray = t => {
  let s = []
  const n = t.length
  for (let i = 1; i <= n; i++) {
    s = s.concat(t.slice(n - i, n - i + 1))
  }
  return s;
}

console.log(reverseArray([2, 4, 6, 8, 10]))
//  [ 10, 8, 6, 4, 2 ]
console.log(reverseArray([3, 6, 9, 12, 15]))
//  [ 15, 12, 9, 6, 3 ]

Ignore that I may have used methods you are not yet familiar with. It still follows a similar pattern to yours.

1 Like

Your explanation is very clear, now I get it! Thanks!

1 Like