While debugging a caching class today, I realized that I had finally been caught by semicolon insertion.
Here’s the original code cut from a larger object literal
1 2 3 4 5 6 7 |
isValid: function(hash) { return // Is cached AND typeof this.entries[hash] != "undefined" && // Cache doesn't expire (e.g.: -1) OR hasn't expired yet (this.entries[hash].expires < 0 || this.entries[hash].expires > new Date().getTime()); } |
After about 10 minutes and a gratuitous amount of debug output, I realized that this function was returning undefined
. “Nonsense,” I said to myself, “it’s returning a boole…wha…wait. Dammit.”
In my effort to document and format at the same time, I dropped the expression to the next line after the return
. Being that return
by itself on a line is a complete and valid expression, JavaScript’s automatic semicolon did its thing and ended the statement there and my conditional expression was never evaluated.
Wrapping the whole conditional expression in parenthesis fixed the problem by invalidating the return
line as a whole statement.
1 2 3 4 5 6 7 8 |
isValid: function(hash) { return ( // Is cached AND typeof this.entries[hash] !== "undefined" && // Cache doesn't expire (e.g.: -1) OR hasn't expired yet (this.entries[hash].expires < 0 || this.entries[hash].expires > new Date().getTime()) ); } |
Let that be a lesson to us all. I suppose it was bound to happen at some point.