Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function not returning the expected result

Tags:

javascript

I have written a function to search an array and log a number(x) if it is found. The code below works as expected and 1 is logged.

let myArr = [54, 23, 499, 342, 1, 44];
let x = 1;

let searchNumber = (arr) => {
  arr.forEach(ele => {
    if (ele == x) {
      console.log(ele);
    }
  })
};

searchNumber(myArr);

I'd like to now return the number that I assign to variable x. Expecting y to be assigned 499 but when I log y it returns undefined. Where am I going wrong?

let myArr = [54, 23, 499, 342, 1, 44];
let x = 499;

let searchNumber = (arr) => {
  arr.forEach(ele => {
    if (ele == x) {
      return ele;
    }
  })
};

let y = searchNumber(myArr);
like image 830
btew2102 Avatar asked Dec 03 '22 09:12

btew2102


1 Answers

return ele inside forEach callback is not the return of the searchNumber function.

forEach executes a provided function once for each array element so return ele inside that will act like return to that provided function inside forEach.

It does not repesent the return to the main function.

In this case, it's better to use for loop.

let myArr = [54, 23, 499, 342, 1, 44];
let x = 499;

let searchNumber = (arr) => {
  for (let i = 0; i < arr.length; i ++) {
    if (arr[i] == x) {
      return arr[i];
    }
  }
};

let y = searchNumber(myArr);
console.log(y);
like image 177
Derek Wang Avatar answered Dec 05 '22 00:12

Derek Wang