Loop inside a function returns "undefined" as the final element

I’m on the “Mini Linter” project … step 3. I know how to solve it in some ways, but wanted to set up a loop inside a function and keep getting the right output, except “undefined” at the end, no matter what I do.

I should just use another method and move on but this is bugging me.

Here is some code:

let unnecessaryWords = ['extremely', 'literally', 'actually' ];

const wordChecker = (arrayName) => {
  let elementPos = 0
  while (elementPos < arrayName.length) {
    console.log (arrayName[elementPos])
    elementPos++ 
    }
  }

   console.log(wordChecker(unnecessaryWords))

I am only using console.log here to check the output of my function … it logs the words in an array as intended, but then always adds one more line “undefined” …

In this example it logs:

extremely
literally
actually
undefined

Even if use a defined number instead of arrayName.length – any number at all, it will still loop through a given array and correctly log the strings, and then end with “undefined”

Even with a “for” loop as well.

Where is this “undefined” coming from?

Hello @dataace52049, welcome to the forums!
I believe the undefined is coming from the fact that you aren’t returning anything from the function, yet you are still console.loging it. Any easy was to resolve this would be to simply call the function:

wordChecker(unnecessaryWords);

Without the console.log(), this line is merely calling the function. Since the function has console.log in it, the words you want will get printed, and no undefined will appear.
I hope this helps!

1 Like