Kyle Waid
Kyle Waid

Reputation: 302

Why ! operator returns true for different expressions?

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?

enter image description here

Upvotes: 2

Views: 62

Answers (2)

Ala Eddine Menai
Ala Eddine Menai

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

Nick Parsons
Nick Parsons

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

Related Questions