Table of contents
Open Table of contents
Article body
In school, our teachers told us that equals compares values, while == compares references. I must have memorized that countless times, but I rarely thought about it at work; my head was full of frameworks instead. Today, that came back to bite me. I needed to compare a value sent from a JSP page with a string defined on the server, and I ended up writing a comparison with ==. The received value and my string appeared identical, yet the if condition was false. I couldn’t see why.
After staring at the code for a while, I suddenly noticed that I had used == for the comparison. It felt as though I’d forgotten everything I’d learned. Perhaps I’d been writing too much frontend code lately and mixed the two up. In JavaScript, the comparison operator I use most often is ==, rather than the strict equality operator, ===.
To put the distinction in one sentence: when comparing strings, equals checks whether their contents are equal, without comparing their memory addresses, whereas == compares references. It returns true only when both references point to the same object; otherwise, it returns false.
For example, the value received from the page is FC, and the server defines String name=“FC”, also containing FC. In the example described here, “FC”==“FC” returns false, while “FC”.equals”FC” returns true.
Just a quick record of a moment when my brain stopped cooperating at work.