Coding for Kids

JavaScript's Math Object

There is a large Math object pre-programmed into JavaScript. It has a lot of useful features that you can use in your coding. Some of the methods are straightforward. Others, I'll discuss a little more.

Getting an Integer (Rounding)

There are actually three ways to get an integer using the Math object.

Syntax:

Examples:

Note: Math.floor(); is used most often because computers index from zero, such as with arrays.

Pi (π)

Very useful for anything involving circles, in particular. Use Math.PI; to return the value of π. Note: no parentheses here.

Absolute Value

Absolute value removes any negative sign from a number and gives you the positive value. No numbers are harmed during this process.

Syntax:

Examples:

Exponential Powers

If you need to raise a number to an exponent, you need to use this method. Raising a number to a power means multiplying itself as many times as the exponent says to.

For example, 47 is 4 * 4 * 4 * 4 * 4 * 4 * 4 which equals 16384.

You can also use negative exponents, as in: 4-7 which is 1/47 or 1/4 * 1/4 * 1/4 * 1/4 * 1/4 * 1/4 * 1/4 or 1/16384 which is 0.00006103515625. Whew!

Use Math.pow(x, y); to compute x to the power of y, or xy.

Examples:

If you need a root of a number, like the cube root, you can put in a fractional (or decimal) exponent. Due to how JavaScript calculates numbers, you may not get a perfect answer. A cube root is a number to the one-third power. A square root is a number to the one-half power, and so on. What about a fourth root?

JavaScript has a shortcut operator ** that does the same thing as Math.pow().

Square Roots and Cube Roots

Although you can use the Math.pow(x,y); method to calculate a square or cube root, the Math object has special methods for square and cube roots.

For a square root, use Math.sqrt(number); This is the same as if you used Math.pow(x, 0.5); or Math.pow(x, (1/2));

For a cube root, use Math.cbrt(number);.

Examples:

Minimum/Maximum

If you pass in a set of numbers, this will return the minimum or maximum value, depending on which method you use.

Examples:

Using Math.min() and Math.max() to keep numbers within a range

Coding for Kids Sidenote: You may not need this next part all that often. Usually you just need to stop a number from being too small (like hit points going below 0) or too high (like only having up to 4 people playing Mario Kart in the living room at once).

These are very useful if you need to keep a number variable bound between within a range. Let's you need a number from 2 to 18 and you have variable n that can change. Note that you use Math.min(); to stop at the top of the range and Math.max(); to stop at the bottom.

In generic form, where range is from low to high, you would use this.

Now your knowledge has exponentiated!

—Dr. Wolf