Skip to main content

Command Palette

Search for a command to run...

Why do we enforce use == over === in JavaScript?

Updated
1 min read

You might think we're crazy at first, but let me explain everything in detail.

An ESLint rule was introduced three weeks ago to ensure engineers consistently use == instead of === when checking for null or undefined.

// null check guidance
    'no-restricted-syntax': [
      'error',
      {
        selector:
          "BinaryExpression[operator='===']:matches([left.type='Literal'][left.value=null],[right.type='Literal'][right.value=null])",
        message:
          'Use == null. `foo === null` returns `false` if `foo` is `undefined`, which is generally not what you want.',
      },
      {
        selector:
          "BinaryExpression[operator='!==']:matches([left.type='Literal'][left.value=null],[right.type='Literal'][right.value=null])",
        message:
          'Use != null. `foo != null` is true if `foo` is neither null nor undefined, which is usually what you want.',
      },
      {
        selector:
          "BinaryExpression[operator='===']:matches([left.type='Identifier'][left.name='undefined'],[right.type='Identifier'][right.name='undefined'])",
        message:
          'Use == null. `foo === undefined` returns `false` if `foo` is `null`, which is generally not what you want.',
      },
      {
        selector:
          "BinaryExpression[operator='!==']:matches([left.type='Identifier'][left.name='undefined'],[right.type='Identifier'][right.name='undefined'])",
        message:
          'Use != null. `foo != null` is true if `foo` is neither null nor undefined, which is usually what you want.',
      },
    ],

The root cause lies in the fact that null is not equal to undefined. Most of the time, we simply want to verify that a variable is neither null nor undefined. However, using === for the check can lead to unexpected results, potentially causing more issues.

💡
This rule applies only to expressions involving null or undefined; for all other conditions, we strongly recommend using === to prevent unexpected type conversions.