dsat
dsat

Reputation: 147

Equality issues in javascript

I don't understand why the last line in this code snippet returns false. Isn't it the same as the line above?

const Statuses = Object.freeze({
  UNKNOWN : 0,
  OK      : 1,
  ERROR   : 2,
  STOPPED : 3
});

class myStatus extends Object{
  constructor() {
    super();
    this.status_id = Statuses.UNKNOWN;
  }
  valueOf(){
    return this.status_id;
  }
  getStatus(){
    return this.status_id;
  }
}

var a = new myStatus();
a.status_id = Statuses.ERROR;
console.log(a == Statuses.ERROR);
console.log(a.getStatus() === Statuses.ERROR);
console.log(a.valueOf() === Statuses.ERROR); //Isn't this the same as the line bellow?
console.log(a === Statuses.ERROR); //Why is this false but the rest are true?

http://jsbin.com/ritumesegi/edit?js,console

I get a == Statuses.ERROR being true, but shouldn't the rest give the same result? Especially the last 2. Isn't

a === Statuses.ERROR

the same as

a.valueOf() === Statuses.ERROR

Upvotes: -1

Views: 63

Answers (3)

Shiko
Shiko

Reputation: 2624

Simply because they are not same type, check below :

console.log(typeof(Statuses.ERROR)); // "number"
console.log(typeof(a) ); // "object"

Difference:
== evaluate values only.
=== evaluate values and types.

Reference:
https://www.w3schools.com/jsref/jsref_operators.asp

http://jsbin.com/jaquzikonu/edit?js,console

Upvotes: 4

CRice
CRice

Reputation: 32176

When using ===, neither value is implicitly converted to anything else.

So in your snippet, STATUSES.ERROR is simply the primitive number value 2, whereas a is an instance of the myStatus class. Since there is no conversion when comparing with ===, it's not surprising that they aren't the same, since one is a primitive value and the other is not.

Upvotes: 1

N-ate
N-ate

Reputation: 6933

a is a myStatus object, so a !== 2, because it is an object.

a.valueOf() is 2.

Upvotes: 1

Related Questions