0

Can someone explain to me the backstage of how implicit coercion in JavaScript works in the following example? Are there any advantages of such behavior? To make myself clear I also show how this would work in Python. Looks pretty simple, but I still do not get the implicit coercion after reading YDNJS up & going.

// JavaScript:
var a = [1,2,3];
var b = [1,2,3];
a == b    // false!!!

var myArr = [12, "string", true];
var myArr2 = [12, "string", true];
myArr == myArr2   // false!!!

## Python:
a = [1,2,3]
b = [1,2,3]
a == b    ## True
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
Fernando Soares
  • 140
  • 1
  • 12
  • There is no implicit coercion going on at all. Python objects can implement `__eq__` to define how `==` should work, whereas JavaScript equality is always reference equality when used on two objects. (The Python equivalent would be `is`.) – Ry- Oct 22 '17 at 13:47
  • what do you mean by reference equality? What would be javascript's equivalent to python's equality? Python 'is' works exactly the same as javascript's '==', but javascript's '===' does not work like python's '=='. I thought there was implicit coercion going on because if you do var c = "1,2,3" you get true at a == c, meaning numbers are no longer numbers. – Fernando Soares Oct 22 '17 at 14:12
  • Correct, `===` also works like `is` when used with two objects. Strings aren’t objects in JavaScript, so that doesn’t apply for `a == "1,2,3"`. JavaScript doesn’t have overloadable operators like Python does; you would write a loop or use an equivalent array function in this case. `a.length === b.length && a.every((x, i) => x === b[i])` – Ry- Oct 22 '17 at 14:15

0 Answers0