Saurabh Tiwari
Saurabh Tiwari

Reputation: 5131

When is the index of array compared with -1

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?

Upvotes: 3

Views: 143

Answers (2)

Aefits
Aefits

Reputation: 3469

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!

Upvotes: 0

Joseph
Joseph

Reputation: 119837

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.

Upvotes: 12

Related Questions