Rule: strict-comparisons
Only allow comparisons between primitives.
Rationale
When using comparison operators to compare objects, they compare references and not values.
This is often done accidentally.
With this rule, >
, >=
, <
, <=
operators are only allowed when comparing numbers
.
===
, !==
are allowed for number
string
and boolean
types and if one of the
operands is null
or undefined
.
Notes:
Config
One of the following arguments may be optionally provided:
allow-object-equal-comparison
allows!=
==
!==
===
comparison between any types.allow-string-order-comparison
allows>
<
>=
<=
comparison between strings.
Config examples
"strict-comparisons": true
"strict-comparisons": [ true, { "allow-object-equal-comparison": false, "allow-string-order-comparison": false } ]
Schema
{ "type": "object", "properties": { "allow-object-equal-comparison": { "type": "boolean" }, "allow-string-order-comparison": { "type": "boolean" } } }
Code examples:
Disallows usage of comparison operators with non-primitive types.
"rules": { "strict-comparisons": true }
Passes
const object1 = {};
const object2 = {};
if (isEqual(object1, object2)) {}
Fails
const object1 = {};
const object2 = {};
if (object1 === object2) {}
Allows equality operators to be used with non-primitive types, while still disallowing the use of greater than and less than.
"rules": { "strict-comparisons": [true, { "allow-object-equal-comparison": true }] }
Passes
const object1 = {};
const object2 = {};
if (object1 === object2) {}
Fails
const object1 = {};
const object2 = {};
if (object1 < object2) {}
Allows ordering operators to be used with string types.
"rules": { "strict-comparisons": [true, { "allow-string-order-comparison": true }] }
Passes
const string1 = "";
const string2 = "";
if (string1 < string2) {}
Fails
const object1 = {};
const object2 = {};
if (object1 < object2) {}