Why do we enforce use == over === in JavaScript?
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.
null or undefined; for all other conditions, we strongly recommend using === to prevent unexpected type conversions.About the author
I have been involved in front-end development since 2007 and have experienced the pre-jQuery, jQuery, and MVVM era. I have a deep understanding of front-end development basics. From 2021 to 2023, I worked as a front-end lead at ByteDance Ltd., the parent company of TikTok.
Comments
Join the discussionNo comments yet. Be the first to comment.
