Working with numbers
So for instance, creating a variable with an integer is as easy as defining it and assigning the number to it:
let n = 42;
And if you want a floating point number, no problem - you can do that just as easily. Simply use a period to separate the whole number and the decimal part, like this:
let n = 42.123;
This also means that you are free to do math with integers and floating point numbers as if they are the same type, which makes things a lot easier. Here's an example:
let n1 = 2, n2 = 40.123; alert(n1 + n2);
When defining large numbers, you may find it hard to see just how big the numbers is when reading the code:
let n1 = 42000000000;
let n1 = 42_000_000_000; alert(n1);
Converting strings to numbers
Sometimes you want to take something that is actually a text string and then convert it into a number. There are two globally available functions for that: parseInt() and parseFloat(). Their names make them quite self-explanatory - they will simply take a text string and, if possible, convert it into a number, assuming that the text string is in the form of either an integer or a floating point number.
let n1 = "40", n2 = "2.42"; alert(parseInt(n1) + parseFloat(n2));
As an alternative, you can use the Number() method - it will try to take any type of input and convert it to a number:
let n1 = "40", n2 = "2.42"; alert(Number(n1) + Number(n2));
Not a Number (NaN)
Here, the parseInt() function is expected to return a number, but "forty two" isn't really a valid number, so to communicate that this wasn't possible, NaN is returned instead. This also means that sometimes, you need to check for NaN, to make sure that the result of an operation was in fact a number. Here, you should use the globally available isNaN() function, which will simply tell you whether the passed value "is Not a Number":
let n1 = parseInt("forty two"); if(isNaN(n1)) alert("Sorry, that's not a valid number!"); else alert("Cool number!");
If you need to work with larger numbers than that, you can use the bigint type, supported by the BigInt object. You can specify a bigint type by calling the BigInt() method on it or by postfixing the number with an n, like this:
let bigNumber = 429007199254740991n; alert(bigNumber); alert(typeof bigNumber);
For most tasks though, you will likely be able to just use the number type - the bigint type is for really, really big numbers, as you can see.
Behind the scenes, when declaring a number, like we did in many of the examples of this article, a Number object is created. On this object, you'll find even more number related functionality, and we'll discuss all of it in the chapter on built-in objects, specifically in the article on the Number object.