-1

Notice the different positions of the words return. How do they actually affect the output differently?

let babyNames = []
const convertToBaby = (arr) => {
  for (let i = 0; i < arr.length; i += 1) {
    babyNames.push('baby ' + arr[i])
  }
  return babyNames
}

const animals = ['panda', 'turtle', 'giraffe', 'hippo', 'sloth', 'human'];
console.log(convertToBaby(animals))

let babyNames = []
const convertToBaby = (arr) => {
  for (let i = 0; i < arr.length; i += 1) {
    babyNames.push('baby ' + arr[i])
    return babyNames
  }
}

const animals = ['panda', 'turtle', 'giraffe', 'hippo', 'sloth', 'human'];
console.log(convertToBaby(animals))
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
Dun Yann
  • 31
  • 2

1 Answers1

-1

TL;DR: You're returning (which stops the subsequent executions) the first run of your loop, in which case, the first iteration will have the value of ["baby panda"]

Elaborated: If you want to see how the loop works, you can give something such as console.log(i), which will in turn output something such as:

0
1
2
...
(size of list - 1, since it started in 0)

So, for instance, if you change to something like:

let babyNames = []
const convertToBaby = (arr) => {
  for (let i = 0; i < arr.length; i += 1) {
    babyNames.push('baby ' + arr[i])

    if (i === 1) {
      return babyNames
    }
  }
}

const animals = ['panda', 'turtle', 'giraffe', 'hippo', 'sloth', 'human'];
console.log(convertToBaby(animals))

The output will be ["panda", "turtle"], because we stopped at the second run of your loop (remember that it started on 0, so i === 1 means its the second iteration)