Open CheatSheet Back To List Next Tutorial

Numbers and Math

Intro

  • This tutorial covers JavaScript Numbers and the Math Object.

  • It is recommended that you follow along with each section below. Paste or type the code into your own JavaScript file and view the variable or expression values either with console.logs or using the VS Code Debug sidebar. 

  • The example code for the entire tutorial series is at github.com/LearnByCheating/javascript-tutorial. There is a separate file or folder for each tutorial, including the To-Do List example project. The Readme file has instructions on how to run the code.



1. Number: data type and global object

  • Number data type: Number is one of the seven JavaScript primitive data types: typeof 7; // returns 'number'
  • Number literal: A number literal is an actual number character such as 7, 3.5, or -53.
  • A number in quotes is not a number, it is a string. typeof '7'; // returns 'string'
  • Arithmetic expressions: Arithmetic expressions resolve to a number literal. For example the expression 4 + 4 resolves to the number 8. 

  • Variable: You can assign a number to a variable. let x = 9; 
Then you can access the value elsewhere in your code: 5 + x; // returns 14 

  • Floating points: In JavaScript, numbers are all floating points, meaning they can have decimal points and the number of decimals is not fixed. It floats depending on the value.
    • So the expression 10/8 resolves to 1.25.
    • The expression 10/3 resolves to 3.333 etc. It cuts it off at some point.
    • 10/2 resolves to 5. 

  • Symbolic number values: The number data type includes a few symbolic values. 
    • NaN: NaN stands for "not a number". It is used to represent a non-number value that has the number datatype: typeof NaN; // returns 'number'
    • Infinity and -Infinity: typeof Infinity; // returns 'number'

  • BigInt: Until 2020 number was the only numeric data type in JavaScript. As part of ES2020 the BigInt data type was added for working with numbers larger than 9 quadrillion.
  • There are two ways to make a number part of the bigint data type:
    • Append the letter n to the number:
let num = 9007199254740992n;
typeof num; // returns 'bigint'
    • Or call the BigInt function and pass in the number as the argument.
num = BigInt(9007199254740992);
typeof (num); // returns 'bigint'

  • The Number.MAX_SAFE_INTEGER property returns the largest number that JavaScript can handle safely outside of BigInt. Number.MIN_SAFE_INTEGER returns the smallest safe number:
num = Number.MAX_SAFE_INTEGER; // returns 9007199254740991
num = Number.MIN_SAFE_INTEGER; // returns -9007199254740991

Number standard built-in object

  • Like other primitive data types, number has a corresponding standard built-in object in the global scope called Number. While not technically a class, you can think of it as a JavaScript class. Number can instantiate objects, and has static and instance properties and methods that you can access to work with numeric data.
Object.getPrototypeOf(7) === Number.prototype; // true

  • When called with the new operator, Number is a constructor function. It will create a number as an object, although style guides recommend using primitive numbers unless you have some specific reason to use a number object.
let num = new Number(7);
typeof num; // returns object.


2. Number function: convert other data types to number

  • You can convert other data types to number primitive values by calling the Number function in a non constructor context, meaning without the keyword new

  • Digit strings (i.e., numbers in quotes) convert to numbers.
let view = Number('7'); // returns 7

  • Empty strings, strings with just white space, null values, and empty arrays convert to 0. 
view = Number(''); // returns 0
view = Number('    '); // returns 0
view = Number(null); // returns 0
view = Number([]); // returns 0

  • Boolean value true converts to 1, and false converts to 0.
view = Number(false); // returns 0
view = Number(true); // returns 1

  • Non-blank stings, undefined, and objects convert to NaN.
view = Number('some text'); // returns NaN
view = Number(undefined); // returns NaN
view = Number({}); // returns NaN


3. Number: static methods and properties

  • So far we've seen that the Number object is a constructor function that can be used to instantiate number objects, and when called in a non-constructor context, it converts values to numbers.
  • Now let's look at static methods and properties. 

ParseInt:
  • We already saw that the Number function will convert strings to numbers. ParseInt is a little more specific.
  • It only returns an integer. If there are any decimal points they get truncated. In the below example we pass in 1.9 we get the integer 1.
let view = Number.parseInt('1.9'); // returns 1

  • Static methods are called directly on the Number class, so you chain it to Number. 
  • However, there are a few static number methods that JavaScript put directly on the global object, including parseInt. So you can call parseInt without chaining it to Number. The below example calls parseInt on the value 2.9 and returns the integer 2.
view = parseInt('2.9'); // returns 2

  • If a string starts with a number and has text after it, parseInt will convert the number and ignore the text. The Number function in this scenario would return NaN.
view = parseInt('3.9 and some text'); // returns 3
view = Number('3.9 and some text'); // returns NaN

  • If the value starts with text it will return NaN.
view = parseInt('This does not work 3.8'); // returns NaN

ParseFloat:
  • ParseFloat parses a sting and returns a floating point number. This is actually very similar to just calling the Number function.
  • In the below example the string 4.1 is parsed to the floating point number 4.1.
view = Number.parseFloat('4.1'); // returns 4.1

  • Just like with parseInt, parseFloat is also available directly on the global object. So you don't have to chain it to Number.
view = parseFloat('5.2'); // returns 5.2

  • If you pass in an integer it just returns the number with no decimal points. 
view = parseFloat('6'); // returns 6

  • Like with parseInt, if a string starts with a number and has text after it, parseFloat will convert the number and ignore the text. In the below example we get 5.2. If we had called Number on it, it would have returned NaN. 
view = parseFloat('5.2 and some text'); // returns 5.2
view = Number('5.2 and some text'); // returns NaN

  • If the string starts with text, then it will return NaN.
view = parseFloat('This does not work 5.3'); // returns NaN

Test numbers
  • There are some static methods that test values and return true or false.

isFinite()
  • IsFinite determines whether the value argument is a finite number. That means it must be of the number data type, and cannot be one of the symbolic number values Infinity, -Infinity, or NaN.
view = Number.isFinite(9999999); // returns true
view = Number.isFinite('9999999'); // returns false
view = Number.isFinite(NaN); // returns false

isNan()
  • IsNaN returns true if the value is the symbol value NaN and false if not.
  • Passing in a string will return false. A string is not the number value NaN.
  • But if you convert text to a number then it will become the value NaN, and isNaN will return true.
view = Number.isNaN('11'); // returns false
view = Number.isNaN(Number('some text')); // returns true

isInteger()
  • The isInteger determines if the argument value is an integer or not. It won't convert data type so any non-number will automatically return false.
view = Number.isInteger(11); // returns true
view = Number.isInteger('11'); // returns false
view = Number.isInteger(11.9); // returns false

isSafeInteger()
  • The isSafeInteger determines if the value is within a safe range. That is between -9 quadrillion and 9 quadrillion. Above that you need to use BigInt when doing calculations or you may run into some precision issues.
view = Number.isSafeInteger(11); // returns true
view = Number.isSafeInteger(Number.MAX_SAFE_INTEGER); // returns true
view = Number.isSafeInteger(Number.MAX_SAFE_INTEGER + 1); // returns false

Static properties
  • Now let's look at Static properties. Properties are like variables that are attached to an object.
  • Number has properties for some constant values. Those are predefined values that never change. There is a convention to put constant value property names in all capital letters. We have several of these but we will just demonstate the ones we have been using.
view = Number.MAX_SAFE_INTEGER; // returns 9007199254740991
view = Number.MIN_SAFE_INTEGER; // returns -9007199254740991



4.  Number prototype: instance properties and methods

  • All objects have an internal property called [[prototype]] whose value is a reference to the prototype object from the constructor function (i.e., class) that created it. The prototype object holds instance properties and/or methods that can be applied to the object. 
  • For primitive values like numbers, the prototype is a wrapper that holds properties and methods to represent and manipulate number values.

  • To find the prototype of a value call the Object.getPrototypeOf method and pass in a number value. The statement below passes in the number 7, and it returns  Number.prototype. 
let view = Object.getPrototypeOf(7); // returns Number.prototype

  • The below function gets the properties and methods on the Number.prototype
view = Object.getOwnPropertyNames(Number.prototype); // returns constructor, toExponential, toFixed, toPrecision, toString, valueOf, toLocaleString

Instance property
  • The constructor property is a reference to the Number constructor function.

Instance methods
  • Instance methods are methods that can be applied directly to the value. 

valueOf()
  • If the number is an object instead of a primitive value, the valueOf method to it will return the primitive value.
let num = new Number(7);
typeof num; // returns 'object'
num = num.valueOf(); // returns 7
typeof num; // returns 'number'

The rest of the instance methods return a string representation of the number values:

toString()
  • The toString method returns the number as a string value.
num = (1995.98).toString(); // returns '1995.98'

toFixed()
  • ToFixed returns the number as a string with a fixed number of decimal points. The argument pass in the number of digits to display after the decimal point. It will round the number if needed. 
num = (1995.48).toFixed(1); // returns '1995.5'
num = (1995.48).toFixed(3); // returns '1995.480'

toPrecision()
  • ToPrecision returns the number as a string. The argument is for the total number of digits to present. It includes both sides of the decimal point. It also rounds if necessary.
num = (1995.48).toPrecision(5); // returns '1995.5'
num = (1995.48).toPrecision(7); // returns '1995.480'

toLocaleString()
  • ToLocaleString returns a string with a language-sensitive representation of the number.
  • Calling it without an argument will present the number based on the language setting in the user's browser. In the US it will use comma separators in the number.
num = (1995.48).toLocaleString(); // returns '1,995.48'

  • The below example adds an argument for German. It returns the number as a string with the number formatting used in Germany.
num = (1995.48).toLocaleString('de-DE'); // returns '1.995,48'

  • The next example sets the language to US English and adds an option to present it as US dollar currency.
num = (1995.48).toLocaleString('en-US', { style: 'currency', currency: 'USD' }); // returns '$1,995.48'



5. Math object

  • Math is a JavaScript standard built-in object. Unlike Number and many of the other built-in objects, it is not a constructor function. So you cannot instantiate Math objects, there is no prototype object, and there are no instance properties or methods.

  • The Math object contains the following properties and methods. We will only cover some of these.
let view = Object.getOwnPropertyNames(Math); // returns abs, acos, acosh, asin, asinh, atan, atanh, atan2, ceil,cbrt, expm1, clz32, cos, cosh, exp, floor, fround, hypot,imul,log, log1p, log2, log10, max, min, pow, random, round, sign,sin, sinh,sqrt, tan, tanh, trunc, E, LN10,LN2, LOG10E, LOG2E, PI, SQRT1_2, SQRT2

Math properties
PI
  • To access a property value, chain it to the Math object. The PI property contains the value of Pi.
view = Math.PI; // returns 3.141592653589793

Math methods
  • To call a method, chain it to the Math object and put the arguments in parentheses. If there are no arguments leave the parentheses empty.

round()
  • The round method will round a number to eliminate any decimal points.
let res = Math.round(1995.95); // returns 1996

trunc()
  • Trunc truncates any decimal points.
res = Math.trunc(1995.95); // returns 1995

floor()
  • If there are decimal points, floor will always round down. 
res = Math.floor(1995.95); // returns 1995

ceil()
  • Ceil will always round up.
res = Math.ceil(1995.01); // returns 1996

max()
  • Max returns the highest value that was passed in as an argument.
res = Math.max(7, -5, 12, 0, 9); // returns 12

min()
  • Min returns the lowest value that was passed in as an argument.
res = Math.min(7, -5, 12, 0, 9); // returns -5

sqrt()
  • Sqrt returns the square root of the argument.
res = Math.sqrt(81); // returns 9

cbrt()
  • Cbrt returns the cubed root of the argument.
res = Math.cbrt(27); // returns 3

random()
  • Random returns a random number between 0 and 1. It is inclusive of 0 but not of 1.
res = Math.random(); // returns a random decimal 0.28477604336688955
res = (Math.floor(Math.random() * 10)) + 1; // returns a random integer 1-10

  • The second statement above returns a random integer between 1 and 10.
    • Since random returns a number between 0 and 1, multiply the result by 10. 
    • Wrap it with Math.floor to remove decimal points from the result. 
    • Then and add 1 so you don't get a 0 result.

  • That concludes this tutorial on Numbers, and the Math object. 


Conclusion

The topics in this tutorial correspond with the JavaScript CheatSheet Number and Math category. Make sure you understand each topic so you can refer back to the CheatSheet when working on your own projects.

If you have the CheatSheet desktop app and downloaded the JavaScript CheatSheet, then go through the flashcards for this category to the point where you can answer them all in order and shuffled.
Open CheatSheet Back To List Next Tutorial