Skip to content

Commit

Permalink
Merge pull request eslint#713 from btmills/eqeqeq-null
Browse files Browse the repository at this point in the history
Relax eqeqeq null check (fixes eslint#669)
  • Loading branch information
nzakas committed Mar 26, 2014
2 parents e1136cb + 19cc7e2 commit 44460ff
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 6 deletions.
4 changes: 2 additions & 2 deletions docs/rules/eqeqeq.md
Expand Up @@ -28,8 +28,7 @@ if (obj.getStuff() != undefined) { ... }

- `"smart"`

This option will enforce `===` and `!==` in your code unless you're comparing between literals
or you're doing a `typeof` comparison. For those types of comparisons using strict equality is unnecessary.
This option will enforce `===` and `!==` in your code unless you're comparing between literals or you're doing a `typeof` comparison. For those types of comparisons using strict equality is unnecessary. It also permits comparing to `null` to check for `null` or `undefined` in a single expression.

The following patterns are considered okay and do not cause warnings:

Expand All @@ -38,6 +37,7 @@ typeof foo == 'undefined'
'hello' != 'world'
0 == 0
true == true
foo == null
```

The following patterns are considered warnings with "smart:
Expand Down
13 changes: 10 additions & 3 deletions lib/rules/eqeqeq.js
Expand Up @@ -18,14 +18,21 @@ module.exports = function(context) {
}

function bothAreSameTypeLiterals(node) {
return node.left.type === "Literal" && node.right.type === "Literal" && typeof node.left.value === typeof node.right.value;
return node.left.type === "Literal" && node.right.type === "Literal" &&
typeof node.left.value === typeof node.right.value;
}

function isNullCheck(node) {
return (node.right.type === "Literal" && node.right.value === null) ||
(node.left.type === "Literal" && node.left.value === null);
}

return {
"BinaryExpression": function(node) {
var operator = node.operator;

if (context.options[0] === "smart" && (isTypeOf(node) || bothAreSameTypeLiterals(node))) {
if (context.options[0] === "smart" && (isTypeOf(node) ||
bothAreSameTypeLiterals(node)) || isNullCheck(node)) {
return;
}

Expand All @@ -36,4 +43,4 @@ module.exports = function(context) {
}
}
};
};
};
4 changes: 3 additions & 1 deletion tests/lib/rules/eqeqeq.js
Expand Up @@ -21,7 +21,9 @@ eslintTester.addRuleTest("lib/rules/eqeqeq", {
{ code: "'string' != typeof a", args: [1, "smart"] },
{ code: "'hello' != 'world'", args: [1, "smart"] },
{ code: "2 == 3", args: [1, "smart"] },
{ code: "true == true", args: [1, "smart"] }
{ code: "true == true", args: [1, "smart"] },
{ code: "null == a", args: [1, "smart"] },
{ code: "a == null", args: [1, "smart"] }
],
invalid: [
{ code: "a == b", errors: [{ message: "Expected '===' and instead saw '=='.", type: "BinaryExpression"}] },
Expand Down

0 comments on commit 44460ff

Please sign in to comment.