Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    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).

    javascriptJavaScript
    Code

    Code

    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
    Transcript

    Transcript

    Instructor: 00:01 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.

    00:12 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.

    00:30 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.

    00:46 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.

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

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

    01:32 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 ===.

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

    Discuss

    Discuss