JavaScript Fundamentals: Understanding Equality (== vs ===)
Welcome to the fourth part of our Node.js Jumpstart series! In Variables and Functions we covered key JS fundamentals. Now, let's tackle a concept that frequently causes bugs: comparing with == vs. ===.
Understanding == vs === (Loose vs. Strict Equality)
This difference is a common source of subtle bugs. JavaScript offers two equality checks:
-
Loose Equality (
==): Compares values after type coercion. Example:console.log(5 == '5'); // true console.log(0 == false); // true console.log(null == undefined); // true console.log('' == false); // true -
Strict Equality (
===): Compares both type and value without coercion. Example:console.log(5 === '5'); // false console.log(0 === false); // false console.log(null === undefined); // false console.log('' === false); // false
Things in life may not be equal.
But in JavaScript? Everything might be... if you use
==instead of===.
Recommendation: Always use === (and !==) to avoid unexpected coercion. Save == (!=) for rare, explicit cases like when you're comparing null to undefined.