0

This is my JavaScript function to check if a particular entry exists or not in an array, but this is always returning null even though there is a match

function getSupplierForId(supplierId) {                               
    data.suppliers.forEach(x => {                                     
        console.log('Current item id : ' + x.id);                     
        console.log('Requested supplier id : ' + supplierId);         
        console.log('Both ids are equal : ' + (x.id === supplierId)); 
        if (x.id === supplierId) {                                    
            console.log(x);                                           
            return x;                                                 
        }                        
    });                                                               
    return null;                                                      
}                                                                     

This is my console output:

Console output

Why is it returning null always?

halfer
  • 19,824
  • 17
  • 99
  • 186
Sony
  • 7,136
  • 5
  • 45
  • 68
  • 2
    Because you have `return null;` at the end. `return` statements do not cross function boundaries. – Felix Kling Mar 04 '20 at 19:41
  • What change should i make inorder to return the match without returning null – Sony Mar 04 '20 at 19:43
  • Good explanation: https://medium.com/@JeffLombardJr/understanding-foreach-map-filter-and-find-in-javascript-f91da93b9f2c – Darius Mar 04 '20 at 19:43

1 Answers1

5

Because you have return null; at the end. return statements do not cross function boundaries. return x; only returns from the inner function (whose caller is .forEach), not from the outer function.

Anyways, the right tool to use in your case is .find:

function getSupplierForId(supplierId) {                               
  return data.suppliers.find(x => x.id === supplierId)  
}    

You might also find my post about callbacks interesting: https://felix-kling.de/blog/2019/javascript-callbacks-misconceptions.html

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143