Is strict equality (===) ever required when comparing any entity to a Symbol? None of the type conversion rules on MDN indicate any conversion to/from a Symbol and a reading of them indicates that it should always be OK (apart from perhaps spoiling code uniformity?) to use == when one of the entities is a Symbol.
So can something like
function foo(x) {
return x == somePredefinedSymbol;
}
ever go wrong, because as far as I understand the above equality can only return true if x is somePredefinedSymbol?
P.S.: This is just for technical curiosity. I don't intend to advocate the usage of ==.
So can something like
function foo(x) { return x == somePredefinedSymbol; }ever go wrong,
Yes, this is a somewhat constructed example but it does showcase a failure scenario:
const predefinedSymbol = Symbol("foo");
const someObject = {
value: "bar", // some unrelated values
[Symbol.toPrimitive]() { // override primitive conversion
return predefinedSymbol;
}
}
console.log(someObject == predefinedSymbol); //true
console.log(someObject === predefinedSymbol); //false
As of ES6 the loose equality will take account of Symbols when compared to an object. From ECMAScript 6 specification, 7.2.12 Abstract Equality Comparison:
- If Type(x) is either String, Number, or Symbol and Type(y) is Object, then
return the result of the comparison x == ToPrimitive(y).- If Type(x) is Object and Type(y) is either String, Number, or Symbol, then
return the result of the comparison ToPrimitive(x) == y.
Therefore, if an object converted to a primitive produces a symbol and that is the same symbol you compare with, then loose equality will produce true but using strict equality the result be false.