My ECMA Proposal : make switch useful

The Switch
The Switch

[update 2014 Nov 04]

Please read this post in conjunction with:  https://dbj.org/dbj-cond/

[end of update]

The other day on jQuery forum, I spotted a code like this one:
(first published 06JUN09)


Unfortunately, for some, this is “too many keystrokes” … And peculiarly (then very young and rushed) Mr B. Eich forgot to make a result of the switch available, so this was not possible in JavaScript:

As far as JavaScript parsers (some of them) are concerned “switch” above is an “unexpected token” error.

Update 2017-10-24

For my browser this (of course) is no longer the case and switch behaves as it should do.  My browser user agent string is this:

Back to distant past. Added peculiarity is that the following code parses OK,

The latest statement is the switch and it returns “red”, indeed. And yes You are free to try and “give it” to the return statement. That might not work too.

One roundabout way is to get to the return value of the switch, with eval(), like this :

The issue is that switch; statement, after all, returns the value, but it is not a legal ‘rvalue’ in some JavaScript engines. At the moment. The eval() trick is not very useful and looks somewhat dodgy. So some developers have concluded they “must help” everyone with the function similar to this:

It has to be said that this is directly inspired by the LISP (COND …) construct. And, by now the excitement in the forum is high indeed because one can safely write this:

Also much cleaner and shorter than the very first snippet in this post. Quick and dirty, and very workable, cond function is this:

Example usage:

For some, this is “Awesome”, while for others this is “obfuscation”. Personally, I like it but I vote for ECMA to simply allow assignment with the ‘switch’ statement to be a legal “rvalue”. That is: make the return value of the switch statement available for assignment:

Although. (It has to be said) I rather like cond() and I think it delivers much more readable robust code. Thus I have added this for everyone to use, to the NPM in the form of dbj.cond() .

Enjoy
–DBJ

Update 2010.Jan.10

Ben Alman made this idea into a useful jQuery plugin, here: http://benalman.com/projects/jquery-cond-plugin/

8 thoughts on “My ECMA Proposal : make switch useful”

Comments are closed.