1

I am to finish the function below. I am to loop through the arr paramteter using a for loop and add the string "Duck" to the end of each element (i.e. arr[0] = "yellow"; should become "yellowDuck".

Here is what I am given to start with:

function addDucks(arr, ind) {

  //WRITE YOUR FOR-LOOP HERE
  //For your iterator, declare it with the let keyword, and name it "i"


  //DO NOT TOUCH THIS
  return [arr, ind]
} 

Here is the code I am trying:

function addDucks(arr, ind) {
  for (let i = 0; i < arr.length; i++) {
    return arr[i] + 'Duck';
  }
  return [arr, ind]
}
5
  • What is the issue that you are encountering when running the code you wrote. What do you expect to happen? Commented Jun 4, 2018 at 22:44
  • @bmartin I expect it to pass these tests: should return an array the first element of the returned array should be the passed-in array with "Duck" added to every element the second element of the returned array should be 3 when passed [1, 2, 3], 3 Commented Jun 4, 2018 at 22:45
  • As the answer below states - you are returning the concatenation of only the first element, instead of modifying the array's values. Commented Jun 4, 2018 at 22:48
  • Tell your teacher the right answer is: "You don't use a for loop, that's what map was created for" but if you insist on mutating there is also forEach Commented Jun 4, 2018 at 23:17
  • @HMR I know. I think it's just to make sure we know about for loops as well. Commented Jun 4, 2018 at 23:42

1 Answer 1

1

Your code was close, you were just not changing the reference in the array to be the string with Duck added. Modified the return arr[i] + 'Duck' to arr[i] += 'Duck' which is the same as arr[i] = arr[i] + 'Duck'

function addDucks(arr, ind) {
  for (let i = 0; i < arr.length; i++) {
      arr[i] += 'Duck';
  }
  return arr;
}
let ducks = addDucks(['green','purple'], 2);
console.log(ducks);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.