Writing better javascript – Part 1
Since I have taken a deep dive into the world of JavaScript programming for a while now, I thought I would start a series of posts with some of the lessons learnt and some good JavaScript programming practices I follow to make my life easier. Here goes the first post …
Always use the “===” operator over the “==” operator unless you explicitly want to.
The difference between the “===” operator and “==” operator is that the “===” makes sure that the types of the values you are comparing are also equal whereas the “==” operator doesn’t. Well, what does that really mean? Well, take the example below
if(test === 3) { alert(“‘===’ evaluated to true.”);}
if(test == 3) { alert(“‘==’ evaluated to true.”);}
In this case “test === 3” comparison will evaluate to false because the variable ‘test’ contains the string ‘3’ and it is being compared to the number 3. Whereas “test == 3” comparison will evaluate to true because the ‘==’ operator ignores the types of the values being compared.
In most cases, you will want to do a ‘===’ comparison and not the ‘==’ comparison. Getting into the habit of always using the ‘===’ operator will help to avoid certain error conditions which are normally hard to locate and debug.
Retro-fitting the === operator to existing code should probably be avoided though as I’ve found that in many cases applying it causes the code to not function as expected.
Its a useful operator for when writing new code though.