Javascript: coercing to signed integer


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


or change x using the assignment expression:


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…

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: