CodeinWP CodeinWP

Why Use the Triple-Equals Operator in JavaScript?

“Determining whether two variables are equivalent is one of the most important operations in programming.” That’s according to Nicholas Zakas in his book JavaScript for Web Developers.

In other words, throughout your scripts you’ll probably have lines resembling this:

if (x == y) {
  // do something here
}

Or, if you’re conforming to best practices, this:

if (x === y) {
  // do something here
}

The difference between those two examples is that the second example uses the triple-equals operator, also called “strict equals” or “identically equal”.

JavaScript beginners who try to adhere to best practices may be using triple-equals and not double-equals, but might not fully understand what the difference is or why it’s important to stick to triple-equals.

What’s the Difference?

In a comparison using the double-equals operator, the result will return true if the two things being compared are equal. But there’s one important catch: If the comparison being made is between two different “types” of values, type coercion will occur.

Each JavaScript value belongs to a specific “type”. These types are: Numbers, strings, Booleans, functions, and objects. So if you try comparing (for example) a string with a number, the browser will try to convert the string into a number before doing the comparison. Similarly, if you compare true or false with a number, the true or false value will be converted to 1 or 0, respectively.

This can bring unpredictable results. Here are a few examples:

console.log(99 == "99"); // true
console.log(0 == false); // true

Although this can initially feel like a good thing (because the browser seems to be doing you a favour), it can cause problems. For example:

console.log(' \n\n\n' == 0); // true
console.log(' ' == 0); // true

In light of this, most JavaScript experts recommend always using the triple-equals operator, and never using double-equals.

The triple-equals operator, as you’ve probably figured out by now, never does type coercion. So whenever you use triple-equals, you’re doing an exact comparison of the actual values. You’re ensuring the values are ‘strictly equal’ or ‘identically equal’.

This means that, using triple-equals, all the examples from above will produce the correct results:

console.log(99 === "99"); // false
console.log(0 === false); // false
console.log(' \n\n\n' === 0); // false
console.log(' ' === 0); // false

What About Inequality?

When doing a not-equals-to expression, the same rules apply. Except this time, instead of triple-equals vs. double-equals, you’re using double-equals vs. single.

Here are the same examples from above, this time expressed with the != operator:

console.log(99 != "99"); // false
console.log(0 != false); // false
console.log(' \n\n\n' != 0); // false
console.log(' ' != 0); // false

Notice now that the desired result in each case should be “true”. Instead, they’re false — because of type coercion.

If we change to double-equals, we get the correct results:

console.log(99 !== "99"); // true
console.log(0 !== false); // true
console.log(' \n\n\n' !== 0); // true
console.log(' ' !== 0); // true

Conclusion

As mentioned, you’ve probably already used triple-equals pretty exclusively. While researching this article, I learned a few things about this concept myself.

I think the best summary comes from Zakas again, where, after recommending always using strict equals, he says: “This helps to maintain data type integrity throughout your code.”

44 Responses

  1. msankhala says:

    Really Good Article. Thanks Louis. Me too using === instead of == but don’t know what it actually do.

  2. One thing you need to look out for: when you retrieve data from a form it’s always a string. So if you ask a visitor to type a number in a text field (or select a number from a select menu) and then compare that value to a number in your programming, the strict equals will be false. You’ll need to manually cast that form value as a number. For example:

    var x = document.formName.fieldName.value; // for example then number 9
    console.log(x===9); // returns false, because x is a string ‘9’
    x = parseInt(x,10); // turn x into an int
    console.log(x===9); // returns true, because x is now an integer

  3. itoctopus says:

    It is worthy to note that the triple equality works the same way in PHP – I don’t know who copied the concept from who though!

  4. Tumbleweed says:

    Yes, different comparison operators based on type … in a loosely-typed language. Makes perfect sense.

  5. Job says:

    I strongly disagree with the triple equal diktat.
    Both have their uses, and if you know JavaScript, using both will never ever be a problem.
    Please JS developers, stop supporting JSLint stupid and narrow vision of JavaScript.

    • Marrowmaw says:

      I agree with you on this however I think unless you are 100% sure you know what you are doing with the language you are much safer to be using strict comparisons.

    • RM says:

      Totally agree with Job:

      and would rephrase: “, and if you THINK you know JavaScript, and find yourself wondering which one to use…” do yourself a favor, step back, understand first what Object Oriented paradigm is all about (in any programming language) so you know when two variables are equal and when two objects state are equal. Otherwise you are “wrapping” your misunderstanding of OOP with a “==” vs “===” decision.

      • Doug DesCombaz says:

        I agree (because I see it used when there is no possibility of coercion (or ambiguous coercion rather)), but with the practical caveat that you generally work with other people.

        1) Although all engineers believe their code is 100% self-documenting, when there is a possibility of coercion (or I suppose some even unknown property types considering its a dynamically typed language),
        ‘==’ may be ambiguous, and the intention of the developer may be difficult to discern by merely reviewing code.

        2) Consistency may be slightly more pleasing on the eye, and we all know how important beauty is.

    • Erik D says:

      100% agree with you.
      For example, consider the following code:
      let node = range.startContainer,
      endNode = range.endContainer,
      startOffset = range.startOffset,
      endOffset = range.endOffset;

      if (node == endNode && node.nodeType == 1 && startOffset == 0 && endOffset == node.childNodes.length)
      return [node];

      I already know that node is of type Node so I don’t have to use tripple-equals and I also already know for a fact that the offsets are numbers. Why spam the tripple =.
      Use it in the right context. But people these days are just lazy or something.

  6. Jenni says:

    Very useful idea, | always use double-equals in Javascript before but after reading your article, I’ll consider using triple equals instead.

    Thank you

    • Ryan says:

      Dont consider it, just do it. The number off oddities you can get by using “==” is quite large and they can be next to impossible for a human to foresee in advance.

  7. Hector says:

    Fantastic article thanks mate :)

  8. rokcrow says:

    Everything clear.
    Helpful post.
    Thanks Lazaris.

  9. Mirza says:

    Thanks for the article.

    I agree with the other commenter saying both have it’s uses. If they didn’t, there would only be one way of checking equality of variables, not two.

    I recommend “horses for courses”. Use the equality operator you need for the purpose you need to use it for. For example, there are times when you want 0 to equal to false. If you use 0===false, you will never get true. While 0==false is true. See what I mean?

    Mirza

    • The only thing I would say to that is that, from a strictly JS perspective, 0 is not equal to “false”, so there should be no reason for you to want it to be. When you say you want zero to equal false, you’re speaking from a data perspective.

      So in that case, I would personally prefer to set up my logic to get the numeric value, then once I have that, I would set the value to “false” if it was 0. Or else run the false logic branch if you find 0. I think this is much easier to maintain/understand. But that’s just my view, other devs may find your suggestion more useful, so I can certainly see where you’re coming from.

      • Stephen says:

        If I really wanted what Mirza is doing I would convert the int to a boolean via not-not …
        var n = 8;
        var boolOfN = !!n;
        …converts int zero to boolean false, any non-zero int becomes boolean true.

  10. manjunath says:

    very good explanation

  11. Shaswati says:

    compact and knowledgeable

  12. Simon says:

    (This article) === (very complete and useful).

    THANKS !

  13. Neal R says:

    In IE9 it seems === seems enforced. At least we ran into a bug on code that worked well in IE7 but failed in IE9 just because we used == for comparison. The exception seen with == IE9 was this: “Can’t execute freed script”. The forums mislead us gallantly for that exception, btw :). A team member luckily was familiar with === and we tried it and our app started working like in IE7. Could not find any “official” doc saying it is enforced in IE9(More tidbits: we have win7 64 bit+IE9 running in IE7 compat mode and moved from win XP+IE7)

  14. sid says:

    Thanks. Very helpful

  15. Niklas R. says:

    I found this very helpful.
    This was exactly the type of explanation I was looking for.
    Job well done. :)

    Thanks a lot.

  16. Jon Skeet says:

    Performance test in article http://conceptf1.blogspot.com/2014/01/javascript-triple-equals-vs-double-equals-operators.html is showing == in same type is faster. So any benefit to use it?

  17. _nderscore says:

    If you look up the specifications, the behavior of the == operator is completely predictable. If you know how JavaScript’s loose-typed equality operator works, it can even be useful in some cases.
    http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3

  18. YourFriend says:

    Nice information about equality signs. I had a question since I don’t have very much experience in Javascript.

    Does javascript shows error when you do something wrong or it just stays quiet like HTML and CSS ?

  19. Sanjay Andole says:

    Really a good one! Thanks for sharing the info.

  20. Great article!
    Definitely will reconsider my usage on the equality operators.
    Anyone interested can check this article http://rainsoft.io/the-legend-of-javascript-equality-operator/ for detailed explanation on how the equality works.

  21. ColeySauce says:

    As others have said, both operators have their uses. A developer SHOULD understand the given language. By blindly using one or the other you fall into the same traps, granted triple equals is safer in that regard. However, I still think it’s a bad idea to tell someone, “stop thinking, just use triple equals”.

  22. Luis says:

    I love the examples of unexpected results you get when you use double equals ==. Really scares you into using triple equals : ) Found a bunch of other scary examples on Stack Overflow: http://stackoverflow.com/a/38856418/984780

  23. Crucial Programmer says:

    This youtube video demonstrates this concept well:

    https://youtu.be/T9VNn0bUXxo

  24. Gentlexp says:

    Thank you for this useful info I always use double-equals in Javascript but after reading I will use triple equals.

  25. The recommendation to always use === is bad advise.
    In fact in most cases when testing values in js you want ==
    Anyone who says otherwise simply doesn’t understand the language operators.
    If you know how each of == and === work you’ll use each one appropriately and get the most out of the language.
    For a couple of quick examples:
    If ur working with numbers and your values may be strings (ie keys parsed from json for example or from an input element) then you’ll want to use ==, like 2 == ‘2’;
    If you have 2 values that may be null, false, undefined, ”, and even perhaps 0 youll usually want == because in practice usually these values are effectively the same (ie not set or empty).
    If you just wanna test if something is truthy or falsey youll usually just want to test it verbatim or !negated like if (!val) vale= 1; // ofc being careful of string ‘0’ etc.
    I propose that if you truly know how == and === both work and use them appropriately then you will very rarely need to use === and you will also find that overuse of it will cause you more problems than under-use.
    If you don’t believe me why not you study == and === and start asking yourself what is most appropriate per case rather than just believing the incorrect ‘best practice’ advise.
    Iv been coding for 35 years btw and I see complete misuse and even breaking use of === every day, and ofc it embarrassingly reveals is that the coder doesn’t understand what they are doing.
    I even recently saw a young coder who read the supposed ‘best practice’ trying to correct a coder who correctly used == which was again embarrassing to anyone watching who knew the language.

    • If ur working with numbers and your values may be strings (ie keys parsed from json for example or from an input element) then you’ll want to use ==, like 2 == ‘2’;

      I think the whole idea behind using only triple equals is that you are encouraged to ensure the things you’re comparing are the same type before they’re compared. So in a case like the one I quoted from you, if I’m expecting a number, then I’m going to make sure that they’re both numbers before I do the comparison. But if they’re not both numbers when I do the comparison, then I want to know about that too.

      For example, why would you even want 2 to be equal to ‘2’? I don’t see how that makes sense. One is a string, the other is a number. Those should never be equal IMO.

      • Eugene Reuben Crispian Kerner says:

        Your comment suggests that haven’t been coding for very long, or at least you havent studied and understood the features of js. == and === are each features of js, and the only reason you would want to disregard a feature is if you don’t understand its usage. There are many cases where you care about value and not type. For example values retrieved from inputs, you know they are strings, you don’t need to test for that or convert them. Same often goes for JSON, especially keys. A handy usage of the feature is undefined == null returns true while undefined == false returns false and null == false returns false, handy to test if a boolean is set. There are so many cases and in fact, I know 100% any js developer who properly understands the == feature will hardly ever use === When I see === throughout code it just shows me that the developer doesn’t have a competent understanding of the language.

        • When I see === throughout code it just shows me that the developer doesn’t have a competent understanding of the language.

          And yet, Douglas Crockford recommended triple equals for years as a best practice. Are you saying that he doesn’t understand the language?

          I get what you’re trying to say, but the entire idea behind using triple equals exclusively was to make code consistent and easy to maintain. Developers can add all sorts of ‘smart’ things to their code but are they maintainable down the road? Not all developers have the same experience, so this sort of best practice considers that and doesn’t assume that everyone has a full grasp of all the features of the language (some of which are bad and shouldn’t be used).

          If you retrieve data from an input that’s a string, but you’re expecting a number, then you can easily fix that by simply converting that data before it’s compared to something else. That’s not difficult to do, and the consistency in the code will be much more readable and maintainable IMO (and in the opinion of other experienced developers).

          All that being said, I think experienced developers like yourself are fine to use double equals and triple equals as needed. But if a less experienced developer takes over your code base, there might be a few challenges to overcome.

          • Eugene Reuben Kerner says:

            More likely Douglas Crockford knew that you wouldn’t understand it. It doesn’t make the code more maintainable. It does make it more consistent if you refer to consistently semantically incorrect. Look what we have here is you stuck on an idea that you’ve never tested or proven yet you are arguing. So there is no point arguing with you when you aren’t arguing based on anything other than incorrect opinion. If one day you want to actually be able to stand behind your word you may want to open a js sandbox and try some stuff. But what would I know, Iv only been coding for 36 years.

          • More likely Douglas Crockford knew that you wouldn’t understand it.

            No, he simply knew that it’s not worth understanding because you can avoid all the problems by simply always using triple equals. Does that mean all developers should do it? No, not necessarily. With your experience, you’re able to do it. But don’t expect a new developer to take over for you and have the same easy time with that codebase.

            It does make it more consistent if you refer to consistently semantically incorrect

            I’m suggesting that data be properly typed before comparisons are made. I don’t know why you say that’s semantically incorrect. It’s like you’re assuming the data has to be in the exact form it was received, otherwise it somehow loses it’s sacredness or something? lol huh?

            Look what we have here is you stuck on an idea that you’ve never tested or proven yet you are arguing.

            There’s no need to test anything. It’s simply a fact that using triple equals ensures that data with different types are not coerced. Maybe you like your codebase like that. A lot of developers don’t. That’s fine, it’s just a matter of preference, and many in the industry agree with this view.

            If one day you want to actually be able to stand behind your word you may want to open a js sandbox and try some stuff.

            Because triple equals is so difficult to understand that I need a JS sandbox for that? Ok…..

            But what would I know, Iv only been coding for 36 years.

            I don’t have a problem with your view on this, I just think using both double equals and triple equals is a somewhat negligible gain at best and a very detrimental one at worst, so I choose to go with triple equals exclusively. But you’re entitled to your opinion based on your experience.

            Also, you’re free to do a full write-up on why you think double equals is fine to use, I’d be happy to read it and even share it with my audience.

  26. Karen betty says:

    Amazing explanation

  27. Patricia says:

    This wouldn’t be an issue if it were a strictly typed language … “convenience” often leads to “comes back to haunt you”

Leave a Reply

Comment Rules: Please use a real name or alias. Keywords are not allowed in the "name" field and deep URLs are not allowed in the "Website" field. If you use keywords or deep URLs, your comment or URL will be removed. No foul language, please. Thank you for cooperating.

Markdown in use! Use `backticks` for inline code snippets and triple backticks at start and end for code blocks. You can also indent a code block four spaces. And no need to escape HTML, just type it correctly but make sure it's inside code delimeters (backticks or triple backticks).