Sunday 13 March 2011

How do you determine if a number is an integer in JavaScript?

x = 1;
x === Math.floor(x);
// returns true
But what happens if we try to add a method for this to the Number prototype?
Number.prototype.isInteger = function() {
return this === Math.floor(this);
}
x = 1;
x.isInteger();
// returns false!
Why? It turns out that when you add methods to Number, the type of the number inside the method becomes "object" rather than "number", but Math.floor returns a result of type "number". If you use the === operator, the two values are no longer equal because they're different types. So the method can be fixed two ways.
Solution 1 is to avoid comparing types:
Number.prototype.isInteger = function() {
return this == Math.floor(this);
// works but breaks if you care about 0 vs other falsy values
}
Solution 2 is better; cast "this" to the Number type and then the types are equal.
Number.prototype.isInteger = function() {
return Number(this) === Math.floor(this);
}
Do you keep a diary (or the more manly version…a journal or chronicles)? Or do you wish to keep notes where the notes keep the date automatically? Well here is an awesome trick for you. All you need is notepad. 1) Open a blank notepad file. 2) Type .LOG in all caps at the top and hit enter. 3) Now save the file. 4) After closing the file, reopen it and notice that the date & time is now listed on the second line. 5) Also notice that the cursor is ready for you to start typing on the very next line. 6) Now every time you open it, type something on the next line and then save it, when you reopen it, it will have automatically saved the date and time on the last line. Try it Now !