× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

All things being Equal (== and === in javascript)

Huw Nichols
Feb 29, 2016
<p>The last few days I've been helping out a few peeps who are new to javascript and I keep seeing instances of lines like this:</p> <p><code>if (someVariable == 'a string') ....</code></p> <p>Please, save yourself and others a ton of pain and just <strong>don't use ==</strong>. It works fine so long as you can guarantee 100% that the type on the left matches the type on the right. Trouble is it's not often in the real world you can always know this. Worse it can change later from a bug or refactoring and so on.</p> <p>The problem is best illustrated with some simple examples (go ahead try them in the js console in your browser):</p> <p><code>false == 'false' // false</code></p> <p><code>'false' == false // true</code></p> <p><code>'' == '0'        // false</code></p> <p><code>0 == ''    // true</code></p> <p><code>0 == '0'   // true</code></p> <p>As you can see, not exactly logical or easy to remember, very hard to catch in complex code as well.</p> <p>Once again, save yourself soem pain, <strong>Use === and not ==</strong></p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus