zoloft pills

Javascript shorthand for string comparison

I’ve decided to write a short article just to keep up the momentum.

Very often, we do something like this:

1
2
3
4
var string1 = document.getElementById("textbox1").value;
if (string1 == "test" or string1 == "staging" or string1 == "dev" or string1 == "internal" or string1 == "beta") {
   document.getElementById("banner").innerHTML = "This app is not the live app!";
}

The string comparison part is just tedious.

Try to do this instead

1
({test:1, staging:1, dev:1, internal:1, beta:1})[string1]

and so the demo block becomes

1
2
3
4
var string1 = document.getElementById("textbox1").value;
if (({test:1, staging:1, dev:1, internal:1, beta:1})[string1]) {
   document.getElementById("banner").innerHTML = "This app is not the live app!";
}

Very neat huh? If the string matches one of those in the associative array, it will return 1, and else undefined. If you want to go even more fancy, try out the operator ‘in’:

1
2
3
4
var string1 = document.getElementById("textbox1").value;
if ((string1 in {test:1, staging:1, dev:1, internal:1, beta:1})) {
   document.getElementById("banner").innerHTML = "This app is not the live app!";
}

Or even this…

1
document.getElementById("banner").innerHTML = document.getElementById("textbox1").value in {test:1, staging:1, dev:1, internal:1, beta:1} ? "This app is not the live app!" : "";

What other rarely-used shorthands can you come up with?

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
One Response
  1. Un says:

    Implement a suffix and prefix tree for doing a string comparison.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>