3

I have seen multiple codes where index of arrays are compared to -1, like

if (index === -1) 

What does this exactly do?

I believe we can't store values in negative index, at least as array element. (I know, As a property of array, we can indeed do that). But then when will the above condition return true or false?

1
  • 1
    As addition to @Joseph the Dreamer answer: for "beauty" comparison sometimes used bitwise operator '~'. It equals expression -(n+1). So you can write it like if ( ~str.indexOf(...) ) { console.log('Found!') }. Commented Sep 15, 2015 at 13:01

2 Answers 2

12

This is usually used with an array's or string's indexOf operation. indexOf returns a -1 when the value is not in the array. Otherwise, it returns a zero-based index of the first match it finds.

The condition you have above probably checks if an item does not exist in the array.

Sign up to request clarification or add additional context in comments.

2 Comments

And yes, before anyone asks, it is reliably -1, not just a negative number, for Array#indexOf and String#indexOf (and Array#findIndex). Naturally YMMV with other functions, check their specification.
... and -1 was specifically chosen because, as OP mentions, "we can't store values in negative index", so it's suited for the "not found" value.
0

consider below code

var fruits = ["Banana", "Orange", "Apple", "Mango"]; var index = fruits.indexOf("Apple"); if(index != -1) { alert ("Apple found at " + index) } else { alert ("Apple not in exists") } 

array indexof returns index number(0 or 1 or 2) of the value if the value exists but returns -1 if the value does not exists.

thanks!

4 Comments

Think you have that comparison backward. In any case, Joseph already covered this ground several minutes ago.
Did not see his reply when I started typing my answer and it took some time when i was typing my answer and Joseph was little faster than me.
@Shahid index value in your code will be 2. Why should Apple found at + index be shown when index=== -1 be true
@Suarabh - I have corrected the if condition thanks for pointing out.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.