Why indexOf can find the index of my object inside array of same class objects?

Viewed 145

I'm doing a study of how javascript objects and its operations works and I found this one that I cannot explain. I'm attaching some code:

// first I create an object
var n = new Object ()

var array_obj = []

// now I create 6 more object of the same class and push it into the array
for ( var i = 0; i < 6; i++) {

    var newobj = new Object()
    array_obj.push( newobj ) 

}

// finally I push my first object into it
array_obj.push( n ) 

console.log( array_obj.indexOf( n ) ) //  output -> 6

At first I thought It could be related to the === that indexOf performs, but after testing with a custom function I found that the single comparation also works ( == ).

Why is this happening? How does it works?

PS: Custom function

findObject( n )

function findObject ( object ) {

    for ( var i = 0; i < array_obj.length; i++ ) {

        if ( object === array_obj[i] ) { // same happens if "==" is used instead

            console.log( i )

        }

    }

 }
1 Answers

First thing you gotta know about Objects (in javascript) is that they are assigned by REFERENCE and NOT by value. With that in mind, every time you declare a variable and assign it with a javascript object, you are storing the reference to the object's address in memory.

when you use indexOf with javascript objects, you are comparing memory address of the OBJECTS and not from the CLASS. Everytime you use NEW with a class (that returns a javascript object) you are instantiating an object from a specific class and returning the address of the OBJECT that you can store at a variable (in this case, it is 'n').

When you use indexOf(n), the function will search for the memory address of the object stored in 'n' and return it's index location inside the array. The others objects you created inside the loop (even being from the same class) will have an unique memory address for each one.

The reason why it will work with both == and === is that When you use === you will compare objects address to check if they are equal. When you use ==, it will make a type cast before comparing. Example, if you compare a string with a number using ==, it will convert one type into another and then will compare their values.

Related