Ternary operators returning functions in Javascript

Here’s something interesting you can do with Javascript:

var ten = 10;
var five = 5;

var returnLargerNumber = five < ten ? function() {
    return ten;
} : function() {
    return five;
};

console.log(returnLargerNumber());

Basically, we are assigning var returnLargerNumber an anonymous function based on the result of the ternary if operation. By calling returnLargerNumber() later, you’ll get either ten or five. Simple enough.

If you want to test your mad javascript skillz, open up your favorite code editor and re-write returnLargerNumber as a simple function with a standard if-else statement.

 

 

When I first read this code, I was pretty sure it just does something like this:

var returnLargerNumber = function() {
    if (five < ten) {
        return ten;
    } else {
        return five;
    }
}

Since I’m still talking about this, you probably already assume that it does something else.

Let’s take another look at the initial code.

var ten = 10;
var five = 5;

var returnLargerNumber = five < ten ? function() {
    return ten;
} : function() {
    return five;
};

console.log(returnLargerNumber()); // logs 10

var five = 9999;

console.log(returnLargerNumber()); // logs 10

What actually happens, is that the ternary operator is evaluated once, and var returnLargerNumber is assigned a function based on the result. And then the function stays there. Even if the result of the ternary if operator changes. So the function, simplified, would actually look like this:

if (five < ten) {
    var returnLargerNumber = function() { return ten; }
} else { 
    var returnLargerNumber = function() { return five; }
}

We stumbled upon this function in an library built by a very experienced Javascript developer, and it took us two men and many hours to figure out why the code wasn’t working right.

I think the moral of the story is always write simple and obvious code. Especially when it’s Javascript.

Indrek Kõnnussaar

I'm a veteran Wordpress developer, context-driven tester, security enthusiast and the mastermind behind Codelight. I love building stuff that works and fixing stuff that doesn't.

Write me directly indrek@codelight.eu
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×