Let’s take a look at an example here:
Let’s take a look at the syntax:
So, we have a string ‘Befundefinedit’, being actioned by the indexOf method. The only exception is that there’s no string value being passed as a parameter… You could say that parameter is undefined…
That being said, let’s go with a few more examples:
‘This is not a null string’.indexOf(null)
This returns 14. You guessed it, null just got coerced to a string and became ‘null’. The rest is pretty straight forward, as ‘null’ appears at index 14 of the string. I have to admit, I did have a little chuckle when I discovered this some time back.
This returns 9, as 0 after being coerced to ‘0’ is found at index 9 of the string.
x=(1!=0); ‘misconstrued as falsehoods’.indexOf(x)
This is a tricky one… I’ve predefined x with a Boolean value. We can see that I’ve cleverly put both ‘true’ and ‘false’ within the string. Which index will it return, 7 or 16? Keep your answer to yourself for just a little longer while we examine this one…
So what if we change it up a little?
x=(1!=0); ‘misconstrued as falsehoods’.indexOf(!x)
The only difference here is that we’ve passed through x which has also been acted upon by the negation operator, !. As a result, !x is passed, which means false its passed, which is coerced to ‘false’ which results in 16 being returned in this instance.
I have a doozy of a next post that will make your freaking heads spin coming soon. In the mean time, have a great day!