Posts tagged “JavaScript”.

Today’s fun JavaScript trick: switch(true)

Programmers who are new to JavaScript but familiar with other C-syntax languages like C or Java are definitely familiar with the switch statement, but may not be aware of how much more flexible this construct is in JavaScript. In fact, I’ve heard experienced programmers claim that they never use switch statements!

One major difference in the JavaScript switch statement  is the fact that the condition can be any type of variable, not just numeric types. Most obviously, this allows you to use a string or an object, which provides a lot of flexibility. So much flexibility, in fact, that when used with a boolean condition the JavaScript switch can provide a very different type of program flow control.

For example, consider a case where we want to take different actions, respectively, if a number is greater than 100, less than -100, or equal to 0. We could write it as a series of if/else ifs, like this:

if(x > 100) {
    doSomething();
} else if (x < -100){
    doSomethingElse();
} else if (x == 0){
    doAThirdThing();
}

Using a switch statement, this block becomes:

switch(true){
    case (x > 100):
        doSomething();
    break;
    case (x < -100):
        doSomethingElse();
    break;
    case (x == 0):
        doAThirdThing();
    break;
}

Is that any better? Probably not. In fact, it’s a little more clever, which may make it a little harder for other programmers to maintain, which would actually make it worse. However, consider the case where we want to take a specific action if x is greater than 100 or y is greater than 200, or z is less than -100, or if (x + y + z) is greater than 500. We could write this:

if(x>100 || y > 200 || z < -100 || (x + y + z) > 500){
    // um, what?
    doSomething();
}

Using the switch statement, that same code looks like this:

switch(true){
    case x > 100:
    case y > 200:
    case z < -100:
    case (x + y + z) > 200:
        doSomething();
    break;
}

I find the second block much more readable. Is it groundbreaking or radically new? No, but this is just another case where the flexibility of JavaScript’s syntax provides an interesting opportunity for more maintainable, readable code.

An operator from Groovy that I wish was in JavaScript

First off, keep in mind that I’ve never used Groovy, just skimmed a couple of language references, but people I know have used it and like it. In case anyone is not familiar, Groovy is a dynamic language implemented on the JavaVM. It’s commonly used for web development, especially with the Grails framework.

Anyway, having established that I don’t know much about Groovy, I do know that it has a feature that I really wish we had in JavaScript. It’s called the Safe Navigation Operator, and it’s represented as ?. in the code. Quoting the Groovy reference:

The Safe Navigation operator is used to avoid a NullPointerException. Typically when you have a reference to an object you might need to verify that it is not null before accessing methods or properties of the object. To avoid this, the safe navigation operator will simply return null instead of throwing an exception[.]

If it’s not clear from that, here’s a real-world example. Let’s say you have a customer object. That object has an optional attribute address, which is itself an object, and in turn has city, state, and postal code attributes, which are strings. In JavaScript, you could access the State like this:

var state = customer.state.address;

No problem, but what if the customer object doesn’t have an address? That line will throw an exception. We can work around it like this:

var customerState= customer.state ? customer.state.address : null;

But if we get deeply nested objects, the syntax gets really muddy. Using Groovy’s Safe Navigation Operator, we could just do this:

var customerState= customer?.state?.address;

Now, if customer is defined, and state is defined, and address is defined, then customerState has the customer’s state. Otherwise, it contains null. Either way, it never throws an exception, even if none of those objects are defined.

Cases where this could come in handy are data retrieved from deep XML hierarchies, complex nested JSON objects returned by web services, and unpredictable user-entered data.  I’m sure that if JavaScript supported a similar operator I would use it all the time. Kudos to Groovy’s designer, Guillaume Laforge.

JavaScript bitwise arithmetic

I finally got an opportunity yesterday to do something I’ve always wanted to do: use bitwise arithmetic in JavaScript. Why would I want to do that? Mostly because it’s interesting and different, but also because bit-twiddling is something that programmers should just know how to do, whether or not we ever actually have to anymore.

The problem with bitwise arithmetic in JavaScript (and, for that matter, in most other languages) is that it’s almost always the wrong solution to the problem. It’s not 1972 anymore, and we can spare enough RAM to give each boolean value its own variable. Sure, it’s a tiny bit less efficient, but the efficiency cost is more than offset by the increased readability and maintainability of code with meaningful variable names.

So in all but the most performance-critical examples, using bitwise arithmetic smacks of premature optimization and over-cleverness. So imagine my delight when I was given the task of storing at least 2, possibly more, flags in a single database field. We weren’t going to get a second field under any circumstances. Arguments raged about whether to use comma-delimited strings, JSON-encoded objects, pre-defined constants, or something else.

What I arrived at was, I believe, the correct solution given the problem. I’m using an integer to store the booleans, and each bit position in the int corresponds with a single flag. Checking the flags is where the fun comes in. Folks with heavy CS backgrounds are not going to be impressed, but those of us who have honed our skills in interpreted languages will get a kick out of this:

// Check whether the second bit is set in the passed integer
function checkFlag(bitmap){
    var mask = 2; // since 2 in binary is 00000010, this will check the second bit.
    return bitmap & mask
}

The bitwise AND operator (&) takes the bitmap and the mask (which is 00000010 in binary) and returns a new number where bits are only set to 1 if they are 1 in both the bitmap and the mask. So if you pass in 3 (00000011 in binary) as your bitmap, only the bit in the second position appears in both. The operator returns 0000010. Since it’s non-zero, we know it passed the test. If you pass in 4 (00000100 in binary), no bit gets set since no bit is set in both numbers. The operation returns 0, and we know the test failed.

So, given a tricky problem (store multiple boolean values in a single variable), we have a tricky solution that’s a little bit of fun to implement and think about. I would love to hear examples of other legitimate uses for clever JavaScript.