Converting to an int without exception

By Luke Smith on November 25, 2007 11:25 PM

The comp.lang.javascript FAQ has a nifty little trick in the type conversion section for converting anything to an int and rather than possibly getting NaN, you will always receive a number.

It's all about the bitwise OR

The method uses the bitwise OR operator | with a non-impacting 0 operand to leverage the JavaScript native ToInt32 function otherwise unavailable within your code. Simply OR a variable and it will be a number.

var foo;
...much chaos ensues...

foo = foo|0; // convert foo to an int

Similar to the unary + operator, |0 will convert false and the empty string to 0 and true to 1. However, it will also convert invalids, such as undefined, "foo", or function foo() {} to 0.

Cryptic? Yes. Idiomatic? Yes. Nifty? I think so. I don't anticipate using it any time soon, as its applicability seems limited, but still something to have in the tool belt (and never use without annotation).

Check out the FAQ page for more info.

No TrackBacks (http://lucassmith.name/mt/mt-tb.cgi/100)

ls.n

LucasSmith.name

Luke and Heidi

I'm Luke. I am a front end engineer at Yahoo! on the YUI team.

Mostly I write about code stuff, but occassionally I'll mix in some real life. You've been warned.

Archives

Tags

Feeds

Subscribe to feed Recent entries

Content licensed under Creative Commons

Code licensed under BSD license

©2005 - 2010 Lucas Smith

Powered by Movable Type