Tell us what’s happening:
Describe your issue in detail here.
**Your code so far**
function findElement(arr, func) {
let len =arr.length;
let arr1 = [];
for( let i=0; i <len;i++){
if(func(arr[i])==true){
arr1.push(arr[i]);
return arr1[0];
}
else{
return undefined
}
}
}
findElement([1, 3, 5, 8, 9, 10], num => num % 2 === 0);
**Your browser information:**
User Agent is: <code>Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36</code>
**Challenge:** Finders Keepers
**Link to the challenge:**
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/finders-keepers
This code should return this sample output.
the sample output:- findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; }) should return 8 .
findElement([1, 3, 5, 9], function(num) { return num % 2 === 0; }) should return undefined .
your problem is in the return undefined, because if the first element in the array is not true the function will terminate.
function findElement(arr, func) {
let num; //here we declate num but we don't assign a value so num = undefined
for( let i=0; i < arr.length;i++){ // we loop over the original array (we don't need a second array)
if(func(arr[i])==true){
return arr[i];
}
}
return num; // if there is no element returned from the for loop then the function will return num and num is undefined
}
In any function the moment you write return in a line the function will stop executing and will return the code in that line.
Look at the first example and then at your code: What does “first value” refer to? It’s saying it should return 8, but 8 isn’t the first value in the array. Now look at the condition, what does it check? What numbers in the array would fulfill this condition and what is it returning?
The forum is here to help people come to solutions - not to just share them.
Please either refrain from posting working solutions or at least utilize the option to format it as spoilers.
It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.
We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.
Thank you so much for clearing things out, actually this is my first post on this forum and I wanted to help and give back to the community. Again sorry for the inconvenience and next time I will try to follow this approach.