Explain Codes LogoExplain Codes Logo

What is the correct way to check for string equality in JavaScript?

javascript
equality-checking
javascript-operators
best-practices
Alex KataevbyAlex Kataev·Aug 29, 2024
TLDR

For a quick yet accurate string comparison in JavaScript, stick to the === operator:

string1 === string2 // A legendary battle ensues, true only if both warriors are of the same type and value

Refrain from using == avoiding the risk of type coercion truth twist. Stick to what you know and trust, and that is ===.

Prevent those awkward moments when new String("a") === "a" returns false by transforming your String object into a primitive:

stringObject.valueOf() === primitiveString // "Wait, you're not an object" says Primitive.

Whitespace can sneak into places it's not wanted. Add an extra layer of precision with .trim():

string1.trim() === string2.trim() // Even strings need a trim to look tidy!

Check for non-equality with the same precision using !==:

string1 !== string2 // True if the combatants fought with different weapons or tactics

The strict vs loose equality dilemma

Trusting the === for its "whole package check"

The === operator fights for justice by checking both value and type, thus it doesn't consider "5" to be equal to 5 - unlike some other operators we might know.

A warning tale about using ==

The == operator has an innocent face, but with its type-coercion trickery, may lead to unexpected results. It's like telling a baby dog is the same as a hotdog just because they share a name - sounds confusing, right?

Spaces, spaces, everywhere

Whitespace can trick you into thinking two similar strings are different. trim() is like your friendly barber for strings, keeping things neat and tidy.

Who are you: Object or Primitive?

In JavaScript, new String("a") === "a" returns false. It's not a bug! new String("a") is an object, while "a" is a primitive. To compare accurately, convert the object into a primitive.

Cracking the code with YDKJ

Book recommendation alert! "You Don't Know JS" by Kyle Simpson enlightens us on JavaScript equality. So, study hard, and never mix up your equal signs!

Special considerations

A helping hand: JavaScript Equality Table

The JavaScript Equality Table is a great help when predicting equality checks. It's like a crystal ball for JavaScript equality! Use it until you learn the quirks of JavaScript equality.

When mere equality isn't enough

Beyond simple equal checks, sometimes you need to order or compare strings. localeCompare() is your ally for local-aware comparisons.

Keep an eye on performance

Methods like .trim(), conversion may take a toll on the performance. Always measure and consider beforehand if the enhancement is worth it - Just like adding ketchup to a hot dog!

Visualization

Visualising the comparison operators in action:

First string = 🔑 FirstKey "HelloWorld" Second string = 🔑 SecondKey "helloworld"

Attempting to unlock the Treasure Chest === with them both:

🔒.openWith(🔑) // Using the '===' operator

And the results:

🔑 FirstKey "HelloWorld" === 🔒: 🔓 // Keys match exactly, treasure chest opens - Wow, shiny gold coins! 🔑 SecondKey "helloworld" === 🔒: 🔒 // Nope, keys don't match, treasure remains locked - maybe next time, friend!

There you have it: === checks both keys for exact match including the casing. The == is like a rusty key that still opens a few locks, but isn't worth the risk. Stay golden with ===!