3

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.

3
  • 2
    The ,0 denotes the start of the search. It default starts at 0, so this is redundant. Commented Dec 15, 2014 at 19:29
  • 1
    developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… - where have you looked it up? Commented Dec 15, 2014 at 19:29
  • I was doing some google searches but I guess the way I was searching it wasn't really the best way. Now that I look back, I sort of how I didn't find it in my searches. Thank you very much though! Commented Dec 15, 2014 at 19:42

3 Answers 3

3

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.

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

2 Comments

It should be noted that there's no good reason for doing it the way it is in the code example provided, since 0 is the default.
Thank you very much! I would give an upvote but I apparently need 15 rep to do that and I don't have that yet. Gave a check though! :)
2

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).

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.