Basic Algorithm Scripting: Finders Keepers (Works fine without else statement))

function findElement(arr, func) {
  let num = 0;
  for(let i=0; i<arr.length; i++){
    if(func(arr[i])){
      num = arr[i];
      return num;
    }
    else{
      return undefined;
    }
  }
}

findElement([1, 2, 3, 4], num => num % 2 === 0);

Here is the code that I have written using pure programming concepts without using any of javascript array methods (filter(), find()) to name a few. It works perfectly when I remove my else statement and place (return undefined) statement outside the scope of for loop block but it doesn’t work in a simple if-else statement. As per my understanding, a for loop is supposed to run its entire iteration unless a break statement is involved, and in if-else statements, the statement control shall go towards for loop if either of the conditions in if-else is met. Thank you in advance for clearing my concepts.

Got it, return statement is the key here which exits the function. My bad

Hi @maverick_2k19, how are you doing?

So after taking a look at your doubt, I can comment on the following statements

  1. findElement() should either a number(You are returning two different things and those are an Integer and one string named as “undefined”).
  2. while calling the function it expects a number to be returned as I can see in your implementation, therefore when you return the “undefined” text(if the number is not found) then num%2 would never be possible in any case.
  3. When you say [quote=“maverick_2k19, post:1, topic:312552”]
    It works perfectly when I remove my else statement and place (return undefined) statement outside the scope of for loop block but it doesn’t work in a simple if-else statement.
    [/quote], then I am assuming by that time your function has already returned num by that time and therefore all the statements below return statement won’t even have any existence if a function has already returned a value.

Let me know if I was able to address your doubts and problem?

Thank-you for your response, the problem was in else statement, as return undefined would return undefined when the first index of the array fails to pass the if condition, only caveat was that return statement would exit the function due to which for loop will not iterate the rest of the array.