Next.js Discord

Discord Forum

find function not returning hard coded value

Unanswered
Patel posted this in #help-forum
Open in Discord
Hello everyone, in below code returns productForm object instead og "iphone14_gold". Could anyone please explain me how?
let productVal = productFormList.find((productForm: any) => {
              const productDetail = productForm?.dataDetails.find((data: any) => {
                return data?.formField?.id === constants.productKey;
              });
              return "iphone14_gold";
            });
console.log('productVal: ', productVal);

1 Reply

Hi,
.find method is expecting a boolean as a return in the callback function, not the value you want to return

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find#callbackfn

It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise

In JS, an empty string is considered falsy

A string with a length > 1 is considered truthy

E.g.:

!!"" // => false
!!" " // => true
!!"iphone14_gold" // => true


So when you return "iphone14_gold", .find understand "this is the object (productForm variable) I'm looking for"