Farhad Khan
Farhad Khan

Reputation: 139

Instance equality check returning false?

I have created a simple Vector class in JavaScript with a constructor and some methods. The add method returns a new Vector instance. When comparing the return value of the add method with a new instance declared with the same values false is returned. I have also tried changing the equality operator to a double equals so I believe the issue is not to do with references.

class Vector {
  constructor(components) {
    this.length = components.length;
    this.contents = components;
  }

  add(vector) {
    if (this.length === vector.length) {
      let a = [];
      this.contents.forEach((cur, index) =>
        a.push(cur + vector.contents[index])
      );
      return new Vector(a);
    }
    throw Error;
  }

  subtract(vector) {
    if (this.length === vector.length) {
      let a = [];
      this.contents.forEach((cur, index) =>
        a.push(cur - vector.contents[index])
      );
      return new Vector(a);
    }
    throw Error;
  }

  dot(vector) {
    return this.contents.reduce(
      (acc, cur, index) => (acc += cur * vector.contents[index]),
      0
    );
  }

  norm() {
    return this.contents.reduce((acc, cur) => (acc += Math.pow(cur, 2)), 0);
  }

  equals(vector) {
    return this.contents === vector;
  }
  toString() {
    return this.contents.toString();
  }
}

let a = new Vector([10, 20, 30]);
let b = new Vector([5, 15, 25]);

console.log(new Vector([15, 35, 55]));
console.log(a.add(b));

//Why does the log below return false?
console.log(new Vector([15, 35, 55]) === a.add(b));

Upvotes: 0

Views: 497

Answers (2)

L483
L483

Reputation: 227

You should not compare two distinct objects with == nor with ===, if you want to test on object equality (see also MDN Web Docs Comparison Operators).

In the case of objects these both operators only return true, if the same object is referenced.

Look at this question on how to test for object equality, because that seems to be what you want to achieve. See here for the difference between object equality and object identity.

Upvotes: 1

Alex R
Alex R

Reputation: 3311

When comparing arrays using === you are comparing their addresses. Check it out:

> a = [1,2]
[ 1, 2 ]
> b = [1,2]
[ 1, 2 ]
> a === b
false

If you want the check if the arrays contain the same elements, you could iterate over all elements and compare them. See this question.

By the way, you should also write throw **new** Error() (without the asterisks).

Upvotes: 1

Related Questions