0

I ran into this case while working with find function for Arrays in Javascript.

I would like to understand how Javascript engine handled the arrow function expression when I had wrongly put curly braces "{ }" inside it.

//Array Declaration
const phones = [{ brand: "Samsung", id: 10 }, { brand: "Apple", id: 20 }];

//correct way
let phone = phones.find(phone => phone.id === 10);
console.log("Correct result: ", phone);

//wrong way
phone = phones.find(phone => {
  phone.id === 10;
});
console.log("Wrong result: ", phone);

Correct result: {brand: "Samsung", id: 10} Wrong result: undefined

1 Answers1

1

Array.prototype.find() expects a Boolean to be returned. In the first example you are implicitly returning phone.id === 10.

In the second example you are not using implicit return because you have used {}. You need to explicitly return the value using return keyword.

phone = phones.find(c => {
   return phone.id === 10;
});
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73