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 )
}
}
}
npoints at the same memory address asarray_obj[6], so they are identical.n != {...n}to be true. They're completely identical, but are separate objects in memory, so they are not equal.