Javascript: coercing to signed integer

2007-11-13

If you have some JavaScript value in x and you want it as a 32-bit signed integer then you can use the expression:

x|0

or change x using the assignment expression:

x|=0

This leaves 32-bit signed integers untouched, and does plausible things for fractional values, very large numbers, strings that look like numbers, true and false, NaN, infinities, and any other objects. It can’t raise an exception. It’s very short.

I can’t remember what I was trying to do when I discovered this, so I haven’t got a good use case…

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: