Ecmascript 6 Features 11: Numbers and Math
Welcome to this week's (rather late - sorry about that! I've been out for much of the week) ES6:Features post. This week, I'll be looking at the ne wadditions to the Number and Math objects.
Firstly, there's a pair of new utility functions that have vbeen added to the Number object called Number.isNaN() and Number.isFinite(), and they can be used (as you might expect) to check to see whether a given number is not actually a number or is infinitely large respectively. Here's a few examples:
Number.isNaN(NaN); // true
Number.isNaN(359); // false
Number.isFinite(9478); // false
Number.isFinite(Infinity); // true
Number.isFinite(-Infinity); // true
The next addition is another checking function that you can use to make sure that a number is within a 'safe' range. The way that javascript interpreters or compilers work means that numbers arree manipulated with a fixed number of bits allocated to represent them. This means that there will be a limit to the size of the number that the interpreter or compiler can accurately represent. Since we have both 32 and 64 bit machines at the moment, this limit moves around from machine to machine - hence the addtion of the following function:
Number.isSafeInteger(56); // true
Number.isSafeInteger(39458634957629746293846); // false
A word of warning though: isSafeInteger, as the name implies, works only with whole numbers - so you'll probably need to run any floats through Math.floor() first, or the next new function that's been added: Math.trunc().
Math.trunc() will drop the fractional part (i.e. anything after the decimal point) of any number passed into it. This can be useful for all sorts of things, including using the function above. At first glance you might think that this function is similar to Math.floor(), but it's not. The difference is that if you feed it a negative number, it still chops the fractional part off, rather than rounding it to the next number down:
Math.trunc(-44.44); // -44
Math.floor(-44.44); // -45
After running a test on jsperf.com, I discovered that the new function is a bit slower than Math.floor and Math.ceil (108M ops/sec vs 116M ops/sec), but this is to be expected with a new function, and the difference shouldn't really be noticeable unless you are doing something really extreme :)
The last new addition is the Number.sign() function. This function is another one for convience. It returns 1 if the number is greater than 0, -1 if the number is less than 0, and 0 if the number is 0 exactly. Here are a few examples:
Number.sign(768); // 1
Number.sign(-356); // -1
Number.sign(0); // 0
That concludes this post about the new number related functions added in ES6. Most of them are for convienence, but they should improve the readability of your code a little bit. At least they aren't as confusing as Symbols! Next time I will probably be looking at the new functions added to the String object.