Can't get why this works this way? To which type js converts item with value = 0 and why ?
if([1,2,0,1].find(item => item === 0)) {
console.log(1); // logs nothing
}
console.log(0 === 0); // logs true
find returns the element it found, and 0 is falsy so if(0) never runs the conditional block.
You should use if (arr.includes(0)). Alternatives that would also work, but are more ugly, are
if (arr.some(item => item === 0))if (arr.findIndex(item => item === 0) > -1)if (arr.find(item => item === 0) !== undefined)It doesn't logs because the result of code below returns 0 which is a falsy value.
const a = [1,2,0,1].find(item => item === 0)
console.log(a) //a is 0
So the statement inside if block doesn't get executed.
If you run [1,2,0,1].find(item => item === 0) in the console, you'll see the output is 0. So it does find your element and returns it.
Then, why is there no 1 printed from console.log? That's because 0 is falsy, and you are now doing if (0), so your condition is never true.
There are multiple solutions to this, depending on the use case some make more sense than others:
1) Check explicitly for !== undefined
if ([1,2,0,1].find(item => item === 0) !== undefined) { /* ... */ }
If find doesn't find anything matching your criteria, it returns undefined, so checking if the return value isn't undefined you'll know the element was found.
Downside: If undefined is a possible value that may actually be searched for, this yet again fails.
Also, this would only make sense if in your real code you'd store the found element in a variable to not only check for its existence but also use it for something else later, otherwise one of the other two options below would be a better choice.
2) Use some instead of find
Since you are just interested in whether something was found, and not which element exactly, you could just use some which returns true/false instead of find which returns the found element itself.
if ([1,2,0,1].some(item => item === 0)) { /* ... */ }
3) Use includes to directly look for the element by value
Since you seem to just have an item === someValue check, you don't really need to use one of the methods that take a callback in the first place, since you could specify the element by value and use includes, which returns true/false:
if ([1,2,0,1].includes(0)) { /* ... */ }