Unlike many other programming languages that separate integers and floating-point numbers into different types, JavaScript uses one unified Number
type to account for numbers. This means you can work with whole numbers, decimals, and even special numeric values all under the same Number
data type umbrella.
Here’s a basic example showing you integers, floating point numbers, and negative numbers are all of type number:
const wholeNumber = 50;
const decimalNumber = 4.5;
const negativeNumber = -7;
console.log(typeof wholeNumber); // number
console.log(typeof decimalNumber); // number
console.log(typeof negativeNumber); // number
JavaScript’s Number
type includes various kinds of numeric values, ranging from simple integers and floating-point numbers to special cases like Infinity
and NaN
, or “Not a Number”. Let’s break down the main types you’ll encounter. Integers are whole numbers without any fractional or decimal part. They can be positive, negative, or zero. Here are some examples:
const positiveInteger = 100;
const negativeInteger = -25;
const zero = 0;
console.log(typeof positiveInteger); // number
console.log(typeof negativeInteger); // number
console.log(typeof zero); // number
Floating point numbers are numbers with decimal points. They’re often referred to as just “floats” by JavaScript developers. Floats are useful when you need more precision, such as when you’re dealing with measurements or currencies. Here are some examples:
const floatingPointNumber = 4.5;
const anotherFloat = 89.56;
const oneMoreFloat = 16.462;
console.log(typeof floatingPointNumber); // number
console.log(typeof anotherFloat); // number
console.log(typeof oneMoreFloat); // number
JavaScript can represent numbers that are beyond the maximum limit with Infinity
. You’ll encounter this when you try to divide a number by zero or on rare occasions, exceed the upper boundary of the Number
type. Here’s an example:
const infiniteNumber = 1 / 0;
console.log(infiniteNumber); // Infinity
console.log(typeof infiniteNumber); // number
Sometimes in JavaScript, some mathematical operations don’t result in a valid number. For instance, if you try to perform a mathematical operation on something that isn’t a number, you’ll get NaN, which stands for “Not a Number”:
const notANumber = 'hello world' / 2;
console.log(notANumber); // NaN
Surprisingly, the type of NaN is also Number
:
const notANumber = 'hello world' / 2;
console.log(typeof notANumber); // number
Apart from the standard decimal system (base 10), JavaScript also supports numbers in different bases such as binary, octal, and hexadecimal. Binary is a base-2 system that uses only digits 1 and 0. Octal is a base-8 system that uses only digits 0 to 7. Hexadecimal is a base-16 system that uses digits 0 to 9 and letters a to f, like you see in CSS hex colors.