Moshe George
Moshe George

Reputation: 310

Inconsistent results of using indexOf on an array in an if-statment

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']);

Upvotes: 0

Views: 169

Answers (1)

volter9
volter9

Reputation: 735

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.

Upvotes: 5

Related Questions