FAQ: Code Challenges: Intermediate JavaScript - reverseArray()

I like your solution! However I’m kind of confused as to how it works. Doesn’t the forEach method start with index 0 then moves through all the rest? My logic is telling me it should just return the same array that you put in, how is this working in reverse?

Hello, I wanted to share my solution. Any thoughts?

const reverseArray = arr => { const newArray = []; arr.forEach(item => newArray.unshift(item)); return newArray; } const sentence = ['sense.','make', 'all', 'will', 'This']; console.log(reverseArray(sentence))

my solution:

function reverseArray(array) {
    let newArray = [];
     for (const i in array) {
     return newArray

I also remembered the method that puts everything at the beginning of the array :slight_smile:

const reverseArray = (array) => {
  const alteredArr = [];
  array.forEach(element =>{
  return alteredArr;

This article greatly helped me - thank you.

I was staring at the spare array with the square brackets, wondering why it was there, and I also didn’t understand why we were using .push, although I think I understand, now…

Hey, can anyone let me know why this solution does not count as a viable answer?

const reverseArray = array => { let newArray = []; for (let i = -1; i >= (0 - sentence.length); i--) { newArray.push(array.slice(i)[0]) } return newArray } const sentence = ['sense.','make', 'all', 'will', 'This']; console.log(reverseArray(sentence)) //Returns ['This', 'will', 'all', 'make', 'sense.'] console.log(sentence) //Returns ['sense.','make', 'all', 'will', 'This']

To my understanding, a new array was created and returns the ‘sentence’ array in reverse as requested

Just tossing this out there: Are there any edge cases?

Noticed on line 3 sentence instead of array.

Once that is fixed reverseArray([]) returns [], which is one edge case. Might be moot, though. Make the fix and test again.