Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

If I set the value to find as a variable, why doesn't it work?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 ===.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading