Please enable JavaScript to use CodeHS

JavaScript Tutorial

Math Object in JavaScript

Every JavaScript program launches with a fully loaded Math object already in orbit: pi, square roots, rounding, powers, and random numbers. No import, no setup, just Math. and go.

javascript ~20 min Beginner friendly
The Big Idea

The Math object

JavaScript does something clever to help programmers with everyday math: it provides a built-in Math object loaded with properties (stored constants) and methods (functions) that you can use anywhere, instantly. An object is simply a container that holds related values and abilities under one name, and this one is mission control for all things math.

To use anything on board, you write Math. followed by the name of the property or method you want, like Math.PI or Math.sqrt(25). One important detail: Math must be capitalized! Writing math.PI with a lowercase m will crash your program.

No import needed: in Python you have to write import math before you can touch math.sqrt(). JavaScript's Math object is different: it is always available, in every program, with zero setup. It is already in orbit before your first line of code runs.

Stored Constants

Math properties

The Math object's properties are stored values for famous mathematical constants. Because a constant never changes, there are no parentheses: you don't call it, you just use it. For example, to use pi you type Math.PI, and you can drop it straight into a calculation:

circle.js
let radius = 4;
let circumference = 2 * Math.PI * radius;

console.log("Circumference: " + circumference);
Console
Circumference: 25.132741228718345

This makes calculations super easy. Without the Math object, you would have to type pi's many digits in by hand, or measure a real circle's circumference and radius and divide. Here are more constants stored on board:

constants.js
console.log("Euler's number: " + Math.E);
console.log("Pi: " + Math.PI);
console.log("Square root of 2: " + Math.SQRT2);
console.log("Natural log of 2: " + Math.LN2);
Console
Euler's number: 2.718281828459045
Pi: 3.141592653589793
Square root of 2: 1.4142135623730951
Natural log of 2: 0.6931471805599453

Spot the pattern: properties are written in ALL CAPS, like Math.PI and Math.E. That's a JavaScript tradition for values that never change. Methods, coming up next, use lowercase names with parentheses.


On-Board Tools

Math methods

Besides constants, the Math object carries common math operations stored as methods. The syntax looks a lot like the properties, except you add ( ) after the name and put your number inside. Here is the crew roster, where x is a number:

Math.round(x)rounds x to the nearest whole number
Math.ceil(x)rounds x UP to the next whole number
Math.floor(x)rounds x DOWN to the previous whole number
Math.sqrt(x)takes the square root of x
Math.pow(x, y)raises x to the power of y (same as x ** y)
Math.abs(x)the absolute value of x (distance from zero)
Math.max(a, b)the larger of two (or more) numbers
Math.min(a, b)the smaller of two (or more) numbers
Math.sign(x)-1, 0, or 1 for negative, zero, or positive x
Math.sin(x) the sine of x (x given in radians); Math.cos and Math.tan work the same way
Math.random()a random decimal from 0 up to (not including) 1

See some of them in action. Try predicting each result before you press Run:

methods.js
let x = 5.4;
let y = 3;

console.log("Round: " + Math.round(x));
console.log("Ceil: " + Math.ceil(x));
console.log("Pow: " + Math.pow(x, y));
console.log("Sin: " + Math.sin(x));
console.log("Random: " + Math.random());
Console (one possible run)
Round: 5
Ceil: 6
Pow: 157.46400000000003
Sin: -0.7727644875559871
Random: 0.7092446841644187

Wait, 157.46400000000003? Computers store decimals in binary, and some decimals don't fit perfectly, so tiny rounding crumbs like this show up. It's normal, not a bug in your code. And the Random: value will be different on every single run, which is exactly its job.


Interactive

Mission console: test every method

You have clearance to use the console. Type a number, then press a method key to see the exact JavaScript line and exactly what the console would print back. Definitely try a negative number with Math.sqrt...

Math console


        

No error in JS, just NaN! Ask for Math.sqrt(-4) and JavaScript calmly answers NaN, short for "Not a Number." Python would slam on the brakes with a ValueError, but JavaScript keeps flying and hands you NaN instead. That's friendlier in the moment, but sneakier: a NaN can drift through your program silently, so watch for it.


The Fun One

Math.random()

The most popular tool on the ship is Math.random(). It takes no inputs and returns a random decimal that is at least 0 and always less than 1, something like 0.7231589... Every call gives a brand new value, which powers dice games, coin flips, enemy spawns, shuffled playlists, and more.

But games rarely want a decimal like 0.7231589. They want "a whole number from 1 to 6," like a die. Getting from one to the other is a classic three-step recipe every JavaScript programmer memorizes.

Memorize This

The random whole number recipe

To get a random whole number from 1 to N, use:

Math.floor(Math.random() * N) + 1

Read it from the inside out, like a countdown:

Math.random() makes a raw decimal

You get a number from 0 up to 0.999..., never quite reaching 1. Say it hands you 0.7231.

* N stretches it out

Multiplying by N spreads that decimal across the range 0 up to (almost) N. With N = 6, our 0.7231 becomes 4.3386, somewhere between 0 and 5.999...

Math.floor(...) chops off the decimals

Flooring 4.3386 gives 4. Now every result is a whole number from 0 to N - 1, each equally likely.

+ 1 shifts the range

Adding 1 slides 0 through N - 1 up to 1 through N. Our roll lands on 5. A perfect die!

dice.js
// Roll a six-sided die
let roll = Math.floor(Math.random() * 6) + 1;

console.log("You rolled a " + roll);
Console (one possible run)
You rolled a 4

Why floor and not round? Math.round would make the lowest and highest numbers come up only half as often as the middle ones. Math.floor keeps every result exactly equally likely. Fair dice only!

Interactive

Random recipe builder

Watch the recipe work, live. Press Generate and follow one value through all three stages. Keep pressing (or use Generate x25) and the tracking board below fills in: proof that every number from 1 to N really does appear. Then use the checkboxes to sabotage the recipe and see exactly what breaks.

Random recipe builder

Stage 1: raw Math.random() ?
Stage 2: stretch * 6 ?
Stage 3: finish Math.floor(...) + 1 ?

Tracking board: results seen so far (target range 1 to 6)

No launches yet. Press Generate!


Your Turn

Practice problems

Now it's your turn! Open your favorite JavaScript editor (or a CodeHS sandbox) and try these. Remember: no import needed, the Math object is already waiting for you.

1

Circle area

Print the area of a circle with a radius of 6. (Area = pi times radius squared.)

solution.js
let radius = 6;
let area = Math.PI * Math.pow(radius, 2);

console.log("Area: " + area);
Console
Area: 113.09733552923255

Two ways to square: Math.pow(radius, 2) and radius ** 2 both work. Pick whichever reads clearer to you.

2

Cosine cruise

Print the cosine of 3π / 4. (Hint: build the angle out of Math.PI, then feed it to Math.cos.)

solution.js
let angle = 3 * Math.PI / 4;

console.log("Cosine: " + Math.cos(angle));
Console
Cosine: -0.7071067811865475

Check yourself: that's about -0.7071, the famous negative square root of one half. JavaScript's trig methods expect angles in radians, and building them from Math.PI keeps everything exact.

3

Hypotenuse hunter

A right triangle has legs of length 5 and 8. Print the length of the hypotenuse. (Hint: Pythagorean theorem, c² = a² + b², so c is the square root of a² + b².)

solution.js
let a = 5;
let b = 8;

let c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));

console.log("Hypotenuse: " + c);
Console
Hypotenuse: 9.433981132056603

Team-up: this one uses two Math methods together, Math.pow inside Math.sqrt. Chaining Math tools like this is everyday JavaScript.


Check Yourself

Quick quiz

1. What must a JavaScript program include before it can use Math.sqrt()?

2. Which line gives a random whole number from 1 to 10, with every value equally likely?

3. What does console.log(Math.sqrt(-4)) print in JavaScript?

Keep exploring

Mission complete! Compare how Python handles the same math, or put your new Math methods to work inside loops.