Question regarding "Finders Keepers" challenge

Question regarding "Finders Keepers" challenge
0

#1

Hello everyone! I have a doubt regarding how for loops and functions work in Javascript. In this code:
´´´
function findElement(arr, func) {
let num = 0;
for (var i =0;i<arr.length;i++){
num=arr[i];
if(func(num)){
return num;
}
}
return undefined;

}

findElement([1, 2, 3, 4], num => num % 2 === 0);
´´´
Does the for loop continue iterating even after the conditions in the “if” statement have been met (eg, 8 has been returned) or does it stop there? Thanks in advance!


#2

Hello, your code is not clear, would you please, edit, select your code and then click on Preformatted text in your editor?

  1. Okay got the following code.
  1. The if inside a for loop is most of the time used to filter data. i.e For loop will run and checks all elements, but it returns only what has been filtered in the if statement.

  2. Would you please explain more why would like (probably) use if to stop the for loop that you already defined to run until X condition is met? (or are you only asking if it stops it?) In this case it doesn’t stop, it only returns filtered data as I said in 2.


#3

Thanks for the reply. The code is the solution to this challenge: https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/finders-keepers
I´m asking a general question about how for loops work. Do they stop after an “if” condition has been met or do they continue to iterate up until the last element?


#4

In this case, it runs and checks all data, if it (the data) meets the condition stated in the if statement, it will be returned.


#5

Thanks for the reply!


#6

You’re welcome.

Good Luck & Happy Coding!