Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the JavaScript operator === provably transitive?

JavaScript's quirky weakly-typed == operator can easily be shown to be non-transitive as follows:

var a = "16";
var b = 16;
var c = "0x10";
alert(a == b && b == c && a != c); // alerts true

I wonder if there are any similar tricks one can play with roundoff error, Infinity, or NaN that could should show === to be non-transitive, or if it can be proved to indeed be transitive.

like image 360
Ray Toal Avatar asked Oct 01 '11 20:10

Ray Toal


People also ask

What does=> mean in JavaScript?

It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.

What is type coercion in JavaScript?

Type coercion is the automatic or implicit conversion of values from one data type to another (such as strings to numbers).

What does in do in JavaScript?

The JavaScript in operator is used to check if a specified property exists in an object or in its inherited properties (in other words, its prototype chain). The in operator returns true if the specified property exists.


2 Answers

The === operator in Javascript seems to be as transitive as it can get.

NaN is reliably different from NaN:

>>> 0/0 === 0/0
false
>>> 0/0 !== 0/0
true

Infinity is reliably equal to Infinity:

>>> 1/0 === 1/0
true
>>> 1/0 !== 1/0
false

Objects (hashes) are always different:

>>> var a = {}, b = {};
>>> a === b
false
>>> a !== b
true

And since the === operator does not perform any type coercion, no value conversion can occur, so the equality / inequality semantics of primitive types will remain consistent (i.e. won't contradict one another), interpreter bugs notwithstanding.

like image 101
Frédéric Hamidi Avatar answered Oct 18 '22 15:10

Frédéric Hamidi


If you look at the spec (http://bclary.com/2004/11/07/#a-11.9.6) you will see that no type coercion is being made. Also, everything else is pretty straightforward, so maybe only implementation bugs will make it non-transitive.

like image 21
deviousdodo Avatar answered Oct 18 '22 15:10

deviousdodo