Numbers in JS

In some programming languages like Python, numerical data is strictly categorized: numbers without decimal parts are Integers, and fractions are Floats. JavaScript simplifies this by categorizing all numerical data under a single type: Number.

The Number Type

In JavaScript, numbers are written without quotes. Because there is no distinction between integers and floats, the Number type seamlessly handles whole numbers, decimals, and negative values.

let x = 2;      // this is a number
x = 5.69;       // this is also a number
x = -5.42;      // yup, still a number

Basic Arithmetic

You can perform standard mathematical operations on numbers as you would expect:

let sum = 2 + 3 + 7;        // 12
let difference = 5.3 - 2.1; // 3.2
let product = 2 * 3;        // 6
let quotient = 6 / 2;       // 3

Practical Example

Tracking metrics is essential for analytics. You frequently need to calculate totals and averages based on the types of messages sent. Because all numbers are of the same type, you can easily combine integers to find averages that result in decimals.

const promoMessages = 12;
const reminderMessages = 15;
const welcomeMessages = 8;
const supportMessages = 5;

// Calculating the sum of all sent messages
const totalMessagesSent = promoMessages + reminderMessages + welcomeMessages + supportMessages;

// Calculating the average per category
const averageMessagesSent = totalMessagesSent / 4;

console.log("Total messages:", totalMessagesSent);
console.log("Average messages per category:", averageMessagesSent);