Skip to content

Instantly share code, notes, and snippets.

@codfish
Last active August 29, 2015 14:21
Show Gist options
  • Save codfish/3d7e55790ce17c32f692 to your computer and use it in GitHub Desktop.
Save codfish/3d7e55790ce17c32f692 to your computer and use it in GitHub Desktop.
JS tip to cast to an Integer, avoiding any NaN pitfalls. "Something to watch out with this approach is for the number to lie within the boundaries of a signed 32-bit integer (or from -2147483648 to 2147483647, inclusively.) Otherwise use your usual Math.floor(). This limitation stems from the fact that we're technically doing a bitwise operation…
// It will always return an integer (never NaN) and will set v to 0 if it was not a number.
// Credit: http://qr.ae/ftLRB
v = ~~v;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment