Reputation: 99
if(arr.indexOf(element))
if(arr.indexOf(element) !== -1)
if(arr.indexOf(element) > 0)
I thought that when I use indexOf()
in an if
statement, those if statements above would be the same, but I got a different result than I expected.
Is there anyone who knows the difference among these?
Upvotes: 0
Views: 1053
Reputation: 205
Assuming this is a JS question, All three are different.
There is no special logic for indexOf within an if statement. It is the same logic as ever. You just need to understand how indexOf() evaluates. The first checks if the index is truthy or falsey, so ONLY the first index would not qualify and all other indexes would pass. The second checks that it is not -1, anything would pass except values not in the array, and the third checks if the index of the element is greater than 0 so all pass except the first index and any element not in the index.
Upvotes: 2