Saturday, July 10, 2010

Conditional Operators and Bracket Notation

Did you know it is valid JavaScript to use conditional operators inside bracket notation to access object properties? For whatever reason, I have only just now realized this.

In other words, this is a perfectly valid fragment:

var obj = {
  valid: [],
  invalid: []

items.forEach(function (item) {
  obj[item.isValid() ? "valid" : "invalid"].push(item);

The conditional operator, which takes the form condition ? ifTrue : ifFalse, is a shorthand version of an if statement. In this case, it results in the name of the object property that I wish to access.

I am yet undecided on whether this is more or less readable than the verbose version:

items.forEach(function (item) {
  if (item.isValid()) {
  } else {

Perhaps I will look back on this post in a few months and marvel at how obvious it all seems in hindsight. In the meantime, it is nice that I am still learning new things about JavaScript.