Reputation: 302
Consider the following javascript
var test = ['1', '2', '3'];
In the console, type
test.indexOf('1') > -1;
Result will be true.
Now add the basic Not operator !.
!test.indexOf('1') > -1;
Result is also true, but I expected the result to be false. Why is it true?
Upvotes: 2
Views: 62
Reputation: 2870
You got true
because you negated the left-hand value
!test.indexOf('1')
not the whole expression
!(test.indexOf('1') > -1).
In other words :
!test.indexOf('1') > -1 // expected true
Is not the same as
!(test.indexOf('1') > -1) // expected false
Like Math statements :
5*2+2 // not the same as 5*(2+2)
Upvotes: 1
Reputation: 50684
This is because !
has higher operator precedence than >
, so first, the result of test.indexOf()
is negated, in your example that results in 0 being negated, so it becomes true
. This is then used in the context of inequality, which converts true
to 1
for the comparison. As 1 > -1
you get a result of true
.
Upvotes: 6