Elizabeth
Elizabeth

Reputation: 61

How the indexOf method works in Javascript

I am taking a Javascript class and my instructor used the following code:

 if('question-'.indexOf('question-1')){
//code
 } 

He claims this produces a true result and will execute the code in the code block (and it does work for him). I have tried running this in console, and I always get a -1 result. I am confused on how indexOf works in this case. (I know -1 means not found). But, in this case, some of the characters are there, just not every single one indicated in the string passed into indexOf. Does every single character have to be there and match? Or in this case was it producing a true result because some of the characters were there?

Upvotes: 0

Views: 52

Answers (1)

Quentin
Quentin

Reputation: 943108

Does every single character have to be there and match?

Yes.

Or in this case was it producing a true result because some of the characters were there?

No. It's producing -1, which is a "not found" result, but -1 is a truthy value.

if (-1) { console.log("-1 is a truthy value"); } // This will be logged
if (0) { console.log("0 is a truthy value"); } // This won't be logged
if (1) { console.log("1 is a truthy value"); } // This will be logged

I assume your instructor is trying to demonstrate to you that you can't treat the return value of indexOf as a boolean.

Upvotes: 4

Related Questions