Strange returns in JavaScript

Via Stack Overflow, I’ve just found this from Neil Fraser. What gets returned?

try {
	return true;
} finally {
	return false;
}

The result is consistent in Java, JavaScript and Python. I wrote this snippet on a whiteboard here at Google. For the next couple of weeks engineers passing by would abruptly stop, transfixed by the paradox. Nerd sniping. I now use it during hiring interviews, if the candidate suffers a similar breakdown, I know we’ve got a keeper.

If you haven’t tried it yet, the answer is false. Which makes sense I guess (haven’t dug into the specs, but I’m sure it’s all there).

But what actually happens in the try? Interestingly the statement is executed, but the function just doesn’t return. Consider

var a = 2;
try {
	return a++;
} finally {
	return a++;
}

The answer here is 3.

3 thoughts on Strange returns in JavaScript

    • Yes, which is as expected. I perhaps glossed over it in the post, but with the postfix operator, a will resolve to its current value when returned and only have its new value saved subsequent to that, so we see the result of the first increment (where the return doesn’t actually take place) but not the second.

      A rather patronising example :)

      (function (a) { return a++; })(5); // 5
      (function (a) { return ++a; })(5); // 6

  1. Once in a while, I use that pattern when I need to return data from an object created locally. The finally is a very elegant way of destroying such temporary object. Obviously, this is only needed in unmanaged code, or in case of JS, if that temporary object is inserted in the DOM. Example: http://stackoverflow.com/a/10958973/607874

Let me know what you think

Your email address will not be published. Required fields are marked *