Javascript switch comparson
Posted on 28 Nov 2015, 12:35 p.m.
How equal is equal?
Sometimes you should be careful about the form in which you represent your data.You should always be careful about the form in which you represent your data. And you should always try to represent it in the semantically correctly form.
In some cases you might get unexpected results (read: bugs) when you neglect to the above guidance. I've boiled down an example here, which came about when using an API that had a tendency to return numerical values as strings, but I wasn't until weird behaviour cropped up that I realised what the API was doing.
Take this example:
var dodgyData = "1"; if (dodgyData == 1) { console.log("Do I get logged?"); }
Answer: Yes, it does pass the test log the message.
OK, so "1" and 1, are equal. Based on that, what might you expect from the following ...
var dodgyData = "1"; switch (dodgyData) { case 1: console.log("I don't get logged"); break; default: console.log("But I do"); break; }
Why? Well here's your clue:
var dodgyData = "1"; if (dodgyData === 1) { console.log("I don't get logged"); }
The lesson here is not in how the javascript switch statement works, but why it's important to know what your data types are, and how to treat them.