bikash
bikash

Reputation: 463

Javascript object property value comparison === vs indexOf

I have an object:

var myObj = {name: 'Tom', age : '25'}

Let's say I need to do something in my program if the name is Tom.

This is how I would normally do:

if(myObj.name === 'Tom'){
    //doSomething
}

However I could also make use of indexOf method:

if(myObj.name.indexOf('Tom') > -1){
    // dosomething
}

What I want to know is that :

Is using indexOf better than === operator ? Which one is better or is there still a better way to compare for an object's property value ?

Is there a performance overhead when using === operator when doing string comparisons ?

Oh btw, I'm using this in a node environment.

Upvotes: 2

Views: 3254

Answers (3)

Fahad Azhar
Fahad Azhar

Reputation: 188

indexOf returns the starting index of matching character .. indexOf doesn't tell you if original string is exactly equal to the original string.

'Blue Whale'.indexOf('Whale'); // returns 5 which means Whale exist in the string.

However on the other hand === operator will allow to precisely match the string.

'Blue Whale' === 'Whale';      // returns  false ; 

So if you want to match the exact string use === operator with will also compare the type .

you can read the official documentation of indexOf

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

Upvotes: 0

Dij
Dij

Reputation: 9808

if(myObj.name.indexOf('Tom') > -1){ // is true
    // dosomething
}

will actually check for position of 'Tom' in the string stored in myObj.name, above if block will also be true for:

if(myObj.name.indexOf('To') > -1){ // is true
        // dosomething
    }

whereas

if(myObj.name === 'Tom'){ //is true
    //doSomething
}

this will compare complete strings myObj.name and 'Tom', myObj.name should be equal to 'Tom' otherwise this condition will not pass. this will fail for

if(myObj.name === 'To'){ //is false
        //doSomething
    }

indexOf() compares searchElement to elements of the Array using strict equality (the same method used by the === or triple-equals operator).

so imo, it will be better to use === here since you are searching for full string, because indexOf() might have extra overhead of comparing it against all substrings.

Upvotes: 3

Nina Scholz
Nina Scholz

Reputation: 386560

A strict comparison === is faster as all other kind of comparisons, because of not required type juggeling or like indexOf with comparison, where indexOf is iterating a string or an array for finding an index.

In this case, where you need just a value, then go for a direct comparison.

If you need to check for a substring, then go for indexOf or some other regular expression based checks.

Upvotes: 0

Related Questions