-1

Sorry if there is something wron with my english :( I' ve started learning Java Script and there alot of things that make me confuse I'm going to loop through an array and check if there is any number that I want to find. I tried alot and find out that it's because the position of 'return'. In my understand it's should be the second code to be true, but it's not. can anyone help me please. Here is my code that works:

//Find 3 in Array
var a = [1,2,3,4];
function findX(){
  for (let i = 0; i < a.length; i++){
    if (a[i] == 3){
      return true;
    }
  }
  return false;
}
console.log(findX());

Here is my code that did not work:

var a = [1,2,3,4];
function findX(){
  for (let i = 0; i < a.length; i++){
    if (a[i] == 3){
      return true;
    }
    return false;
  }
}
console.log(findX());// return false with any number
  • 3
    You are returning false after the first iteration in for-loop so you are checking only `a[0] == 3` and after that you are breaking the loop and returning false. If that makes any sense to you – angel.bonev Sep 23 '22 at 11:47
  • Oh, I get it, I did not consider the first element in array which break the loop, thank you very much :) – truong giang vo Sep 23 '22 at 19:21

2 Answers2

1

Correct way, explaination

This is your first script, which works because here you return TRUE on a[i] == 3 and false to the others

var a = [1,2,3,4];
function findX(){
  for (let i = 0; i < a.length; i++){
    if (a[i] == 3){
      return true;
    }
  }
  return false; // <---
}
console.log(findX());

Incorrect way, explaination

And here is the code that didn't work for you because it loops through them all again, the a[i] == 3 assigns true, and then it assigns false again because the return false is inside the for loop.

var a = [1,2,3,4];
function findX(){
  for (let i = 0; i < a.length; i++){
    if (a[i] == 3){
      return true;
    }
    return false; // <----
  }
}
console.log(findX());// return false with any number
FUZIION
  • 1,606
  • 1
  • 6
  • 19
0

The reason why your code is not working is blatantly simple.

If you run this code then it will first run the if Statement and then it will return false.

If you're new to programming then you should know that no matter how deep a return statement is. It will exit the function with the given value.

So the problem is it never reaches the second iteration and returns false.

The solution is to move return false out of the for loop.

var a = [1,2,3,4];
function findX(){
  for (let i = 0; i < a.length; i++){
    if (a[i] == 3){
      return true;
    }
  }
 return false;
}
   

 console.log(findX());// return false with any number
Vin Xi
  • 986
  • 2
  • 11