Vishful thinking…

Writing better javascript – Part 1

Posted in javascript by viswaug on November 18, 2008

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

var test = “3”; //the variable test contains the string “3”
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.

One Response

Subscribe to comments with RSS.

  1. Ronan said, on November 19, 2008 at 3:55 pm

    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.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: