JavaScript numbers can be written with or without decimals.
Syntax
Adding
Numeric strings
Number as an object
NaN (Not a number)
Numbers in JavaScript are always 64-bit floating points. There are 2 ways to write a number.
Integers are whole numbers. They don't contain any period or exponent notation.
const x = 10;
Floaters are numbers that contain a period or exponent notation.
const x = 0.2 + 0.1; // 0.30000000000000004
These types of numbers are never 100% accurate. To solve that problem you will need to do a bit of multiplication and division.
const x = (0.2 * 10 + 0.1 * 10) / 10; // 0.3
You can add two numbers, and it will result to another number.
const add = 1 + 4; // 5
Be careful! Adding a number type and a numeric string value will result in concatenation.
const addWithString = 5 + "10"; // "510"
JavaScript strings may also contain numeric values, and you can do math operations with them as well.
// Subtracting
const a = "10" - "10"; // 0
// Multiply
const b = "10" * "10"; // 100
// Division
const c = "10" / "10" // 1
If you pay close attention, I did not include the addition operation. That's because when you use the addition (+
) symbol, JavaScript will perform concatenation.
const x = "10" + "10"; // 1010
Even though JavaScript numbers are usually created from literals. They can also be created as an object.
// Type number from literal value
const age1 = 29;
// age2 is now an object instance from new Number()
const age2 = new Number("29");
By practice, avoid creating numbers through with the new Number()
keywords.
NaN
is a special keyword in JavaScript that means that a number is not legal.
NaN
is usually produce when you execute a mathemetical operation with a non-number value.
const y = 5 * "Apples"; // NaN
In the code example above I'm doing multiplication with a non-numeric string value, so it results to NaN
.
You can find out if a value is a NaN
if you use the global JavaScript function isNan()
.
isNaN(5 / "Apples"); // true
isNaN()
will return a boolean result.