Skip to content
Advertisement

Function not returning the expected result

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);

Advertisement

Answer

If you look at the placement of the return statement, it is actually within the arrow function being called for each element (ele => {...}). No value is actually being returned from the scope of the function searchNumber.

Try creating a variable in the scope of searchNumber and modifying it from arr.forEach() instead:

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

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

let y = searchNumber(myArr);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement