diff --git a/docs/rules/eqeqeq.md b/docs/rules/eqeqeq.md index 4f75dece172..fbf45bb3f5a 100644 --- a/docs/rules/eqeqeq.md +++ b/docs/rules/eqeqeq.md @@ -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: @@ -38,6 +37,7 @@ typeof foo == 'undefined' 'hello' != 'world' 0 == 0 true == true +foo == null ``` The following patterns are considered warnings with "smart: diff --git a/lib/rules/eqeqeq.js b/lib/rules/eqeqeq.js index 85522c23b03..4b96ef890f8 100644 --- a/lib/rules/eqeqeq.js +++ b/lib/rules/eqeqeq.js @@ -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; } @@ -36,4 +43,4 @@ module.exports = function(context) { } } }; -}; \ No newline at end of file +}; diff --git a/tests/lib/rules/eqeqeq.js b/tests/lib/rules/eqeqeq.js index 85505faab63..98b3fbe3cc2 100644 --- a/tests/lib/rules/eqeqeq.js +++ b/tests/lib/rules/eqeqeq.js @@ -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"}] },