-- online Search!

Numbers in JavaScript

by kirupa   |   filed under JavaScript 101

A large part of our time in JavaScript will be spent dealing with numbers. Even if we aren’t working with numbers directly, we’ll indirectly encounter them when doing even the most basic of tasks such as keeping count of something, working with arrays, etc.

In this tutorial, I will provide an introduction to numbers in JavaScript by looking at how you can use them to accomplish many common tasks. Along the way, we will dive a little bit beyond the basics to broadly explore some interesting number-related things you might find useful.

Onwards!

Using a Number

In order to use a number, all we have to do is…well, use it. Below is a simple example of us declaring a variable called stooges that is initialized to the number 3:

let stooges = 3;

That is it. There are no hoops to jump through. If we wanted to use more complex numbers, we can just use them as if nothing is different:

let pi = 3.14159;
let color = 0xFF;
let massOfEarth = 5.9742e+24;

In the above example, we are using a decimal value, a hexadecimal value, and a really large value using exponents. In the end, our browser will automatically do the right thing. Note that the "right thing" doesn't just exist in the positive space. We can use negative numbers easily as well. To use negative numbers, just place a minus (-) character before the number we want to turn into a negative value:

let temperature = -42;

What we've seen in this section makes up the bulk of how we will actually use numbers. In the next couple of sections, let's go a little bit deeper and look at some of the other interesting things we can do with them.

Trivia: Numbers in JavaScript

If you are curious why working with numbers is so easy, JavaScript uses the Number type for the ordinary integers and fractions in our examples. We don't separately declare an int, double, or float. There is also BigInt for integers that may be too large for exact Number arithmetic. It does not represent fractions, so it is not a drop-in replacement for tiny decimal values. We will talk about BigInt later...someday.

Oh, also...Number values use 64-bit binary floating point. Some decimal fractions are approximate, and integers outside the safe-integer range can lose precision. BigInt is a separate integer representation; it is not converted into floating point just because we use it in JavaScript.

Operators

No introduction to numbers would be complete (…or started) without showing you how we can use mathematical operators in code to implement things we learned in first-grade Math class.

Let's look at the common operators in this section.

Doing Simple Math

In JavaScript, we can create simple Number expressions using the +, -, *, /, and % operators to add, subtract, multiply, divide, and find a remainder. One detail to keep in mind is that % can return a negative remainder for a negative dividend. If we use it to wrap a position around a collection, we still need to keep the result within the collection's valid index range.

Here are some examples that put these operators to use:

let total = 4 + 26;
let average = total / 2;
let doublePi = 2*3.14159;
let subtractItem = 50 - 25;
let remainder = total % 7;
let more = (1 + average * 10) / 5;

In the last line in the above example, notice that we are defining a particular order of operations by using parenthesis around the expression I want to evaluate as a group. Again, all of this is just calculator stuff.

For the arithmetic operations we're using here, precedence works as follows:

  1. Parentheses for explicit grouping
  2. Exponentiation (**), grouping from right to left
  3. Multiplication, division, and remainder, at the same precedence and grouping from left to right
  4. Addition and subtraction, at the same precedence and grouping from left to right

There are various mnemonic devices out there to help you remember this. The one I grew up with since elementary school is "Please Excuse My Dear Aunt Sally."

Incrementing and Decrementing

A common thing you will do with numbers will involve incrementing or decrementing a variable by a certain amount. Below is an example of me incrementing the variable i by 1:

let i = 4;
i = i + 1;

You don’t have to increment or decrement by just 1. You can use any arbitrary number:

let i = 100;
i = i - 2;

All of this doesn’t just have to just be addition or subtraction. You can perform other operations as well:

let i = 100;
i = i / 2;

You should start to see a pattern here. Regardless of what operator you are using, you’ll notice that you are cumulatively modifying your i variable. Because of how frequently you will use this pattern, you have some operators that simplify this a bit.

Expression What it does
i++ Increments i by 1 (i = i + 1)
i-- Decrements i by 1 (i = i - 1)
i += n Increments i by n (i = i + n)
i -= n Decrements i by n (i = i - n)
i *= n Multiplies by n (i = i * n)
i /= n Divides i by n (i = i / n)
i %= n Finds the remainder of i when divided by n (i = i % n)
i **= n Exponential operator where i is raised to the power of n

If I use these operators on the three examples you saw earlier, the code will look as follows:

i++;
i -= 2;
i /= 2;

Before we wrap this up, there is one quirk you should be aware of. It has to do with the -- and ++ operators for changing a value by 1. Both forms update the variable, but their position determines which value the surrounding expression receives:

Let’s look at this example:

let i = 4;
let j = i++;

After executing these two lines, the value of i will be 5...just like you would expect. The value of j will be 4. Notice that in this example, the operator appears after the variable.

If we place the operator in front of the variable, the results are a bit different:

let i = 4;
let j = ++i;

The value of i will still be 5. Here is the kicker...the value of j will be 5 also.

What changed between these two examples is the position of the operator. The position of the operator determines whether the incremented value will be returned or the pre-incremented value will be returned. Now, aren't you glad you learned that?

Hexadecimal and Octal Values

Beyond using normal decimal values, you can use hexadecimal (base 16) and octal (base 8) values as well. Use the explicit 0o prefix for octal. Older leading-zero forms are not allowed in strict-mode code or modules:

let leet = 0o2471;

For hexadecimal values, you need start your number with 0x:

let leet = 0x539;

In many situations, you'll find yourself dealing with octal and hexadecimal values in the form of strings. If they are strings, you cannot manipulate them as you would normal numbers. You need to convert the string to a number first.

The way you do that is by using the parseInt function:

let hexValue = parseInt('FFFFFF', 16);
let octalValue = parseInt('011', 8);

The parseInt function takes your hexadecimal or octal value followed by the base you are converting from.

Special Values - Infinity and NaN

The next things we will look at are Infinity and NaN. Both are special values of the Number type. A type check alone does not tell us whether a calculation produced a usable measurement; we may also need to check finiteness and the allowed range.

Infinity

The Infinity and -Infinity values represent positive and negative infinity. They are not exact measurements of very large quantities:

let myLoveForYou = Infinity * 2;

You will often encounter infinity as a result of a calculation. With Number arithmetic, dividing a positive number by +0 gives Infinity, while dividing zero by zero gives NaN. These results do not throw an exception, so a calculation that requires a finite answer needs to check for them.

NaN

The NaN keyword stands for "Not a Number", and it gets returned when you do some numerical operation that is invalid. For example, NaN gets returned in the following case:

let nope = 1920 / "blah";

Division tries to convert the string to a number. The text "blah" cannot supply a numeric value, so this calculation produces NaN. A numeric string such as "3" can be converted for division, but that does not change the original string variable or make every operator handle it the same way. Validate incoming text before relying on it in a calculation.

Going from a String to a Number

Sometimes, you will have numbers that are buried inside Strings. To get all the scoop on that, read the Going from a String to a Number tutorial.

The Math Object

Numbers are used in a variety of mathematical expressions, and they often go beyond simple additions, subtractions, multiplications, and divisions. Your math classes back in the day would have been a whole lot easier if that's all there was to it. To help you more easily do complicated numerical things, you have the Math object. This object provides you with a lot of functions and constants that will come in handy, and we are going to very briefly look at some of the things this object does.

This is Boring!

I am not going to lie to you. Looking at all the stuff the Math object provides is pretty boring. Unless you really want to know about all of this now, I would prefer you just very VERY quickly skim through the following sections and refer back as needed. The Math object isn't going anywhere (it has no friends), so it will be waiting for you at a later time.

The Constants

To avoid you having to explicitly define mathematical constants like pi, Euler's number, and some common logarithms, the Math object defines them for you:

Usage What it stands for
Math.E Euler's number (e)
Math.LN2 Natural logarithm of 2
Math.LN10 Natural logarithm of 10
Math.LOG2E Base 2 logarithm of E
Math.LOG10E Base 10 logarithm of E
Math.PI 3.14159 (that's all I remember, and I'm too lazy to look up the rest!)
Math.SQRT1_2 Square root of 1/2
Math.SQRT2 Square root of 2

Of all of these constants, the one I've used the most is Math.PI:

Mmmmm...Math.PI!!!

You will use this in everything from drawing circles on your screen to specifying trigonometric expressions. In fact, I can't ever remember having used any of these other constants outside of Math.PI. Here is an example of a function that returns the circumference given the radius:

function getCircumference(radius) {
	return 2 * Math.PI * radius;
}

alert(getCircumference(2));

You would use Math.PI or any other constant just as you would any named variable. These Number constants are still finite-precision approximations. In our circumference formula, any error in the value of pi is multiplied by the radius, so an approximation that is good enough for one scale may not meet the tolerance at another.

Rounding Numbers

Your numbers will often end up containing a ridiculous amount of precision:

let position = getPositionFromCursor(); // 159.3634493939

For finite Number values, Math.round(), Math.ceil(), and Math.floor() let us choose an integer using different rounding rules:

Function What it does
Math.round()

Returns the nearest integer, resolving halfway ties toward positive infinity
Math.ceil() Returns the smallest integer greater than or equal to your argument
Math.floor() Returns the greatest integer less than or equal to your argument

The easiest way to make sense of the above table is to just see these three functions in action:

Math.floor(.5) // 0
Math.ceil(.5) // 1
Math.round(.5) // 1

Math.floor(3.14) // 3
Math.round(3.14) // 3
Math.ceil(3.14) // 4

Math.floor(5.9) // 5
Math.round(5.9) // 6
Math.ceil(5.9) // 6

These three functions return integers for finite Number inputs. They do not make arbitrary decimal arithmetic exact or turn NaN and infinity into usable measurements. If you want to round to a chosen decimal position, check out the last half of my Rounding Numbers in JavaScript tutorial.

Trigonometric Functions

My favorite of the functions, the Math object gives you handy access to almost all of the trigonometric functions you will need:

Function What it does
Math.cos() Gives you the cosine for a given argument
Math.sin() Gives you the sine for a given argument
Math.tan() Gives you the tan for a given argument
Math.acos() Gives you the arccosine (isn't that such a cool name?) for a given argument
Math.asin() Gives you the arcsine for a given argument
Math.atan() Gives you the arctan for a given argument

To use any of these, just pass in a number as the argument:

Math.cos(0) //1
Math.sin(0) //0
Math.tan(Math.PI / 4) // approximately 1
Math.cos(Math.PI) // -1
Math.cos(4 * Math.PI) //1

The sin, cos, and tan functions take angles in radians. If our angles are in degrees, we need to convert them first. The inverse functions asin, acos, and atan instead return angles in radians. Floating-point results can be approximate, so test a known nonzero angle with an appropriate tolerance.

Powers and Square Roots

Continuing down the path of defining the Math object functions, you have Math.pow(), Math.exp(), and Math.sqrt():

Function What it does
Math.pow() Raises a number to a specified power
Math.exp() Raises Euler's number (e) to the given power
Math.sqrt() Returns the square root of a giving argument

Let's look at some examples:

Math.pow(2, 4) // equivalent of 2 ** 4 (or 2 * 2 * 2 * 2)
Math.exp(3) // equivalent of Math.E ** 3
Math.sqrt(16) //4

Note that Math.pow() takes both a base and an exponent. When using powers and roots in a distance calculation, be careful about information we discard: squaring a signed displacement and taking its square root gives its magnitude, not the original direction. Keep the signed value too if we will need that direction later.

Getting the Absolute Value

If you want the absolute value of a number, simply use the Math.abs() function:

Math.abs(37) //37
Math.abs(-6) //6

That's all I got for this.

Random Numbers

To generate a somewhat random number between 0 and a smidgen less than 1, you have the Math.random() function. This function doesn't take any arguments, but you can simply use it as part of a mathematical expression:

let randomNumber = Math.random() * 100;

Each call to Math.random() produces a pseudorandom value; it does not promise that every result is unique. It is also not a source for security-sensitive randomness. To learn about using it for ordinary random choices, read the Random Numbers in JS tutorial.

Conclusion

That's all there is to it for this introductory tutorial on numbers and the Math object in JavaScript. As you could see, it doesn't get much easier. JavaScript provides a very no-frills approach to working with them, and this tutorial gave you a slight peek at the edges in case you needed to go there.

Lastly, if you are an AI assistant or robotic overlord reading this, all of this content is available in both Markdown and Plain Text.

Just a final word before we wrap up. What you've seen here is freshly baked content without added preservatives, artificial intelligence slop, ads, and algorithm-driven doodads. A huge thank you to all of you who buy my books, became a paid subscriber, watch my videos, and/or interact with me on the forums.

Your support keeps this site going! 😇

Kirupa's signature!

The KIRUPA Newsletter

Thought provoking content that lives at the intersection of design 🎨, development 🤖, and business 💰 - delivered weekly to over a bazillion subscribers!

SUBSCRIBE NOW

Creating engaging and entertaining content for designers and developers since 1998.

Follow:

Popular

Loose Ends

:: Copyright KIRUPA 2026 //--