I am trying to check if an array contains a given value:
var arr = [];
if (arr.indexOf(2)) {
console.log('yes');
}
Fiddle
Why is the if condition always met, although arr
does not contain a value of 2
? Shouldn't it return -1
and therefore nothing should be logged?
I am trying to check if an array contains a given value:
var arr = [];
if (arr.indexOf(2)) {
console.log('yes');
}
Fiddle
Why is the if condition always met, although arr
does not contain a value of 2
? Shouldn't it return -1
and therefore nothing should be logged?
-
In JavaScript
Boolean(-1) === true
, soBoolean([].indexof(2)) === true
, butBoolean([2].indexOf(2)) === false
. – David Foerster Commented Mar 14, 2015 at 21:48
3 Answers
Reset to default 4If you run this code in your browser's console, you'll see that it does return -1. However, in a JavaScript if statement, -1 is truthy so the alert will execute. As detailed in this excellent JavaScript equality table, there's only a very few values which will evaluate as false in an if statement: false
, 0
, ""
, null
, undefined
and NaN
.
Your condition should be:
if (arr.indexOf(2) >= 0)
because in JavaScript, 0
is false
when coalesced to a boolean, and any other number is considered true
.
Therefore... -1
is coalesced to true
.
alert(!!-1)
It does return -1 but -1 in Javascript is considered "truthy".
Try this to see that it is indeed returning -1:
var i = arr.indexOf(2);
console.log(i);
You need to explicitly pare for non-equality to -1 in your condition.
Here's an updated version of your jsfiddle:
http://jsfiddle/bmj8y8bj/