Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 593
JoeL Avatar asked Dec 06 '25 08:12

JoeL


1 Answers

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.

like image 80
APerson Avatar answered Dec 07 '25 20:12

APerson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!