Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Compare the == and === Operators in Javascript

    Chris AchardChris Achard

    Both double equals == and triple equals === can be used to compare values in javascript - but they are different in a subtle, but very important way. Double equals == compares just the value of two things - and if the types are different, it will use type coercion to match the types before comparing. Triple equals === compares both the type and value of objects, and both must match before two values are equal.

    The same rules apply for not equal != (compare value only) and not equal, equal !== (compare type and value).



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Instructor: Double equals will tell you if two things have the same value, and triple equals will tell you if two things have the same value and of the same type. Let's look at a few examples.

    5 == 5 is true, but 5 == "5" is also true. What's happening here is that the string "5" is actually being coerced into a number by the double equals and then being checked against the number 5.

    For triple equals, 5 === 5 is true, but 5 === "5" is false. That's where we can really see the difference between the double and the triple equals.

    This can really become an issue with false values in JavaScript, so false == 0is actually true, because false is coerced into the number 0False === 0is correctly false, because 0's number type doesn't match false's Boolean type. There are other values where this applies as well, like an empty string.

    We also have to be careful with null and undefined, because null == undefined is true, but null === undefined is false.

    One other note is that not a number is never equal to anything with either double or triple equals, including not a number.

    All the same rules we just talked about also apply to !=, and !==, with the != having the same rules as == and !== having the same rule as ===.

    The prevailing advice is to always use triple equals as much as possible, because using double equals can sometimes unknowingly get you into trouble.