0

I want to know why v.map(...) is not equal to v.map(...) using the same function to do the map

var v = [1,2,3,4,5]
v.map(function(a) {return a+1}) === v.map(function(a) { return a+1;}) 

Running this on node repl, I've got the result of the second expression as false

Cœur
  • 37,241
  • 25
  • 195
  • 267
Sibelius Seraphini
  • 5,303
  • 9
  • 34
  • 55
  • 7
    Objects are compared by their identity rather than by their similarity. And, `.map()` returns a distinct instance of `Array`, with its own identity, every time you call it. [How to determine equality for two JavaScript objects?](http://stackoverflow.com/questions/201183/how-to-determine-equality-for-two-javascript-objects) – Jonathan Lonowski Apr 04 '16 at 00:04
  • 1
    Also, perhaps, relevant: "[how to check if two arrays are equal with JavaScript?](http://stackoverflow.com/questions/3115982/how-to-check-if-two-arrays-are-equal-with-javascript)" – David Thomas Apr 04 '16 at 00:06

2 Answers2

3

When comparing the equality of non-primitives, Javascript checks equality by equality of reference - that is, do both objects being tested refer to the same object in memory?

In this case, they do not - .map returns a new object, and running .map on the same array two different times will return two different references - regardless of the computations done while mapping.

To sum it all up:

v === v is true because v refers to the same object in memory [1,2,3,4,5] === [1,2,3,4,5] is false because both arrays are different objects in memory (i.e. reference is compared, not values) .map will always return a new instance of an array - so the result cannot be equal to another .map statement

Kevin Kennis
  • 31
  • 1
  • 2
2

This is because arrays are compared by reference, not by value, in Javascript.

In other words, doing something like

[1,2] === [1,2];

returns false in Javascript because the two arrays occupy different locations in memory. They are not compared by the actual contents they may have (which is what we would call comparison by value).

In contrast, doing

var x = [1,2];
x === x;

returns true. In this case, the variable x refers (resolves to the memory location of the array) to the same array and this common reference to a memory location is sufficient to yield true.

map() returns an array. Comparing two arrays by value is a fairly complicated affair in Javascript.

Community
  • 1
  • 1
Akshat Mahajan
  • 9,543
  • 4
  • 35
  • 44