0

I have the following function

function findNeedle(array) {
    array.forEach(element => {
        if(element === 'needle') {
            console.log('needle') // needle
            return 'needle'
        }
    });
}
const needle = findNeedle(['hay', 'junk', 'hay', 'hay', 'moreJunk', 'needle', 'randomJunk'])
console.log(needle)

I don't really understand why my function returns undefined. I tried using forEach and I still have the same issue. The strange thing is that the console.log statement before return 'needle' executes

dbramwell
  • 1,298
  • 6
  • 11
shane_00
  • 101
  • 1
  • 2
  • 9

2 Answers2

1

You have to do this Because it return the needle to forEach function not the findNeedle function

Have a good day and if any doubts comment

function findNeedle(array) {
var answer;
    array.forEach(element => {
        if(element === 'needle') {
            console.log('needle') // needle
            answer= 'needle'
        }
    });
return answer
}
const needle = findNeedle(['hay', 'junk', 'hay', 'hay', 'moreJunk', 'needle', 'randomJunk'])
console.log(needle) //undefined
Lonely
  • 66
  • 7
-2

You must return the array inside your function, else it will result in undefined. Like so:

function findNeedle(array) {
    return array.forEach(element => {
        // ....
}

But you have some other errors in this code.

I am not exactly sure what you are trying to achieve, could this help you?

function findNeedle(arr) {
    return arr.map((element, index) => {
        if(element === 'needle') {
            return index;
        }
    });
}
let needle = findNeedle(['hay', 'junk', 'hay', 'hay', 'moreJunk', 'needle', 'randomJunk']);
console.log(needle)
Elise Chant
  • 5,048
  • 3
  • 29
  • 36