When calling the findProd function with the number 1, everything works correctly. However, if I replace the number 1 with the idToFind variable, the console outputs undefined. Why is this happening?
P.S. in my file, if I print idToFind, the result is 1.
addToCartButtons.forEach(button => {
button.addEventListener('click', (event) => {
const idToFind = event.target.dataset.id;
let array = [{id: 1, name: 'mattia'}, {id: 2, name: 'cesare'}];
function findProd(product) {
return product.id === 1;
}
const result = array.find(findProd);
console.log(result);
})
});
I need to make the comparison value of the function dynamic.
>Solution :
It’s because the event.target.dataset.id
is a string. The strict comparison operator you use compares types first, so 1 === '1'
results in false
.
Notice how you can convert string value to a number value with an unary +
. Then 1 === 1
would result in true
and in consequence, your find
function will work as expected.
addToCartButtons.forEach(button => {
button.addEventListener('click', (event) => {
const idToFind = event.target.dataset.id;
let array = [{id: 1, name: 'mattia'}, {id: 2, name: 'cesare'}];
function findProd(product) {
return product.id === +idToFind;
}
const result = array.find(findProd);
console.log(result);
})
});
Also, the code would benefit in readability from using an array function and converting the identifier to number during the variablie initialization.
addToCartButtons.forEach(button => {
button.addEventListener('click', (event) => {
const idToFind = +event.target.dataset.id;
let array = [{id: 1, name: 'mattia'}, {id: 2, name: 'cesare'}];
const result = array.find((product) => product.id === idToFind);
console.log(result);
})
});
You may want to read more about the strict equality ===
.