I don't understand how some of this works

// Write your code here:
const reverseArray = arr => {
  let reversed = [];
  for (let i = arr.length - 1; i >= 0; i--)
{  reversed.push(arr[i]); }
  return reversed

const sentence = ['sense.','make', 'all', 'will', 'This'];

// Should print ['This', 'will', 'all', 'make', 'sense.'];

Here’s a link to the challenge The Challenge

I struggled for about an hour (I don’t know if that was long enough to think about it on my own - thoughts please!) and looked at stack overflow and MDN documentation but eventually had to look at the code solution. I just don’t understand how some of the code works. Like, was reversed saved into the function reversedArray? Because I can’t see right now how the reversed sentence was called by console.log() at the end.

Also, why aren’t Codecademy letting us use built-in methods for the first few challenges?


This challenge is to practice reversing items in list (they don’t let you use a built-in because you can do this with a built-in, the point is practice with data manipulation).

When you write const reverseArray = arr => {/*code*/} you’re actually writing a function. When it’s written, the code won’t execute until it is invoked. This particular function code takes in an array as variable arr and uses a for loop to create a reverse version of it (by looping backwards through the array and adding copies to a new “reversed” list). Finally, this result is returned.

In programming returning is much more meaningful than console.logs, as it is much closer to a real action. When we console.log(reverseArray(sentence)) we only see the results of what would happen when we invoke reverseArray on sentence. If we wanted to store the value in a new variable, we might write something like

let myReversedList = reverseArray(sentence);
1 Like

Yes, in fact, within the function is the only place reversed exists. It’s declared within the function so as soon as the function is finished, it disappears. The only reason we’re able to console.log() or do anything else with its value is because we returned that value.

If you mean specifically did the reversed version of sentence get saved into the function, then yes - one bit at a time when the loop pushes each word in. After the loop, reversed contains the whole reversed sentence and we return it.

So the reversed sentence wasn’t really called by console.log() per se. The function was called by console.log. The value of that function call is what’s logged, and since we had a return value, that’s what it prints. (In JS it would still have a return value if we didn’t specify one, but it would just be undefined)

Does that help? I’m not sure exactly where your confusion is.

1 Like