0

I am in the process of learning node. The following code is giving me inconsistent result ie, if i give argv1.indexOf('test'), then the code is unable to find the text, but, some time it is returning true. Why is it so.

function process(argv1) {
    if(argv1.indexOf('test')) {
        console.log('Text is available in array.');
    }
}
process(['test','one','help', 'one', 'two']);
2
  • What would you expect indexOf to return in this case? Commented Dec 9, 2014 at 1:18
  • 1
    Did you bother to read the documentation for indexOf? Commented Dec 9, 2014 at 3:12

1 Answer 1

5

That's because indexOf returns an index of matched element. If element not found, it will return -1.

What you need is to change the condition:

function process(argv1) {
    if(argv1.indexOf('test') !== -1) {
        console.log('Text is available in array.');
    }
}
process(['test','one','help', 'one', 'two']);

Edit: As pointed out @Havvy, in case of test, .indexOf will return 0 which would be casted to false. For other array elements, their indices would be converted to true, as any non zero numbers would be casted to true. More about javascript evaluation you can read here.

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

2 Comments

Furthermore, if will typecast the result to a boolean. The value 0 gets typecasted to false, so ['test', 'foo', bar'].indexOf('test') evaluates to 0, and if (0) {} evaluates to false, not executing your block.
Yeah, of course, and if the element index would be more than zero, it would cast to true.

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.