JoeL
JoeL

Reputation: 710

The indexOf method in Javascript

I'm trying to understand a lot of the basic components of Javascript and one of the things I came across is a line of code saying

if (varX.indexOf(String(varY),0) < 0)    

varX being an array of Strings and varY being obviously one of the strings within that array. Take away the ",0" and I understand that the code is just looking for varY withing array varX. But I don't know what the ,0 does and what means for the if statement. I did what I could to look this up and didn't really come across anything.

Upvotes: 3

Views: 105

Answers (3)

Seva Arkhangelskiy
Seva Arkhangelskiy

Reputation: 685

0 is index from where you start the search. It is 0 by default, so you don't have to pass this parameter.

Upvotes: 0

APerson
APerson

Reputation: 8422

According to the MDN docs:

fromindex

The index to start the search at. If the index is greater than or equal to the array's length, -1 is returned, which means the array will not be searched. If the provided index value is a negative number, it is taken as the offset from the end of the array. Note: if the provided index is negative, the array is still searched from front to back. If the calculated index is less than 0, then the whole array will be searched. Default: 0 (Entire array is searched).

So, passing in "0" is pretty much pointless, as it starts off the search at 0 anyway.

Upvotes: 3

Quentin
Quentin

Reputation: 943571

From mdn:

arr.indexOf(searchElement[, fromIndex = 0])

fromIndex

The index to start the search at. If the index is greater than or equal to the array's length, -1 is returned, which means the array will not be searched. If the provided index value is a negative number, it is taken as the offset from the end of the array. Note: if the provided index is negative, the array is still searched from front to back. If the calculated index is less than 0, then the whole array will be searched. Default: 0 (Entire array is searched).

Upvotes: 2

Related Questions