Friday, March 30, 2012

Quick Tip: JavaScript Switch Statement

My friends, even those who are fellow coders, are always amazed by how many books, tutorials, and videos I go through on a regular basis. They assume, for some strange reason, that because I have been doing this for such a long time I should know all that I will ever need to know. I don't think you can ever reach such a point.

I have been programming in JavaScript since the 1990's. Admittedly my early JavaScript programs were amateurish. They were usually just there to do some kind of trick or effect. They were not doing any kind of serious coding. Later JavaScript was included to do both validation and Ajax. Nowadays I write full solutions in JavaScript.

I was reading the book, "Node.js in Action", when I realized that I missed something in JavaScript. For all of my years of coding JavaScript, I have thought that the switch statement required an expression which evaluates to an integer. This is not true. Looking back on things I realize that all of the examples of switch statements I have seen use integers in the case statements, but this is not a requirement of the language. The only thing that the language requires is that the switch and case statement expressions match in value and data type. So long as that is true, everything's a go.

Why was this important? With web programming lots of values are passed as strings, for example HTTP verbs. Now there are better patterns to use instead of long rambling switch statements, however when you have only a few possible values, nothing is more to the point than a switch.

This is perfectly legal JavaScript: