I'm a beginner/intermediate JavaScript programmer and recently got a couple of exercises handed out on job interviews.
I have to write a function in JavaScript called find that takes two parameters, one of which is an arrow function, containing one parameter. The function should find the appropriate object in an array and return it. I have trouble understanding what the arrow function ((toy) => (toy.type === 'car')) does, how it evaluates, how I can use it. toy is not defined, as can be seen in the example, it is just used as a parameter, which I find extremely confusing and puzzling.
Exercise given:
const toys = [{type: "car", color: "red"}, {type: "ball", color: "blue"}, {type: "teddy-bear", color: "brown"}]
const carToy = find(toys, (toy) => (toy.type === 'car'));
console.log(carToy); // expected output: {type: "car", color: "red"}
What I wrote:
function find(array, toy) {
console.log(toy); // [Function (anonymous)]
toy(); // TypeError: Cannot read properties of undefined (reading 'type')
console.log(toy()); // TypeError: Cannot read properties of undefined (reading 'type')
}
At first I thought that toy would evaluate to the string "car", but it doesn't. console.log() inside a find function returns either undefined or [Function (anonymous)].
If I got a string I could easily solve the problem, but the arrow function has had me stuck for over an hour. I have tried to find a solution online, but nothing helped me understand this.
Would love to get some pointers on how to solve this and any in depth resources that would teach me more about arrow functions.
Looks like you need to implement the find method.
What is happening is that the function is passed as a parameter, so to be able to call that function you need to pass it a object of type toy.
Something like this, didn't test it so might require a tweak or two
You can read this Article for a tutorial about this subject