Brevity in JavaScript
Instead of this
var intAge = parseInt(document.getElementById('txtAge'));
Use:
var intAge = document.getElementById('txtAge') | 0;
Written by Prosper Nsengiyumva
Related protips
5 Responses
var
b = '1837727366484959938' | 0; // -1722178816
The purpose of your protip is vague, confusing, and not giving everyone the full story.
First, I have no idea why you are coercing a DOM node to an integer.
Second, if you want to coerce something to a number, you have the unary operator available which is more expressive. This does have the drawback of not truncating to an integer.
var b = +'1837727366484959938'; // 1837727366484959938
var b = +'1.5'; // 1.5
Lastly, as @couto pointed out, while numbers are 64-bit loating point in JS, the bitwise operators coerce those numbers in 32-bits.
As a result, you run into cases where you exceed 2^31
, 2147483648
and entire into one's compliment territory.
Math.pow(2, 31) | 0; // -2147483648
(Math.pow(2, 31) - 1) | 0; // 2147483647
References:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators
http://www.amazon.com/JavaScript-Definitive-Guide-Activate-Guides/dp/0596805527/
Yeah, this only works for small numbers due to the way JS does it numbers. It uses the binary base. I will do a follow-up.