For loop spits out an extra value?

Hi all!

Currently working on this code challenge:

https://www.codecademy.com/paths/web-development/tracks/web-dev-js-arrays-loops-objects/modules/web-dev-intermediate-javascript-practice/lessons/intermediate-javascript-coding-challenge/exercises/shout-greetings

This is what I have:

const shoutGreetings = (greetings) => {

  let newArray = [];

  for (let i of greetings) {

    console.log (`${i}!`.toUpperCase());

  }

  return newArray;

}

const greetings = ['hello', 'hi', 'heya', 'oi', 'hey', 'yo'];

console.log(shoutGreetings(greetings))

// Should print [ 'HELLO!', 'HI!', 'HEYA!', 'OI!', 'HEY!', 'YO!' ]

My output looks like this:

HELLO!
HI!
HEYA!
OI!
HEY!
YO!
[]

I have an extra so it’s not accepting the answer.
Would someone be able to give me some clarity on this?

Specifically, why is this creating the extra ? And how to solve this?

If I delete the empty array and the return array it prints:

HELLO!
HI!
HEYA!
OI!
HEY!
YO!
undefined

I think it’s the return newArray bit. You create an empty array and return it. Without it, it would still log those items.

2 Likes

I think you’ve fallen into a common pitfall that many learners encounter - confusing sending output to the console and returning data from a function.

Inside of your shoutGreetings() function, all you’re doing is iterating over the greetings array you’ve passed in and logging them to the console. You don’t use the newArray value at all, but you return it at the end of the function.

As a result, when you eventually get to this - console.log(shoutGreetings(greetings)) - your function logs the greetings to the console, because that’s what your for loop does. However, the outer call to console.log() also logs to the console the return value of the function, which in your original code is the empty array newArray.

When you’ve removed the newArray variable and the return statement, you’re getting undefined at the end because you’re still logging the return value to the console. In the absence of a defined return value, JavaScript functions return undefined.

The task asks you to write a function which takes an array as input, and returns a new array with those items capitalized. Whatever you output to the console is irrelevant. You can log the capitalized values to the console to check that your code is working, sure, but it’s not the output which is being asked for. :slight_smile:

2 Likes

Ok that makes sense thanks!

I’ve gotten rid of the console.log and i’ve put
newArray.push(i.toUpperCase())

Which makes it upper case, but im struggling to get the ! on the end

return newArray += ‘!’ just adds a ! at the end of YO!

return newArray[i] +="!" gives me a reference error :frowning_face:

Ive got it!!!

const shoutGreetings = (greetings) => {

let newArray = ;

for (let i of greetings) {

i += '!'

newArray.push(i.toUpperCase())

}

return newArray

}

1 Like