Lesson 35 +10 XP

Number Basics

Number Basics

In JavaScript, there is basically one type of number. Integers and decimals are both just number.

Writing numbers

let a = 10;     // integer
let b = 3.14;   // decimal
let c = -7;     // negative

Special number values

  • Infinity: a value larger than any number.
  • -Infinity: smaller than any number.
  • NaN: "Not a Number", the result of invalid math.
10 / 0;        // Infinity
"abc" * 2;     // NaN

Numbers are also objects

Numbers have built-in methods. When you use a method, JavaScript temporarily wraps the number:

(3.14159).toFixed(2); // "3.14"

Number() conversion

Number() converts strings to numbers:

Number("42");  // 42
Number("3.14"); // 3.14

parseInt and parseFloat

parseInt("42px");  // 42
parseFloat("3.14x"); // 3.14

TL;DR

  • JavaScript has one main number type.
  • Infinity and NaN are special values.
  • Number() converts values to numbers.
  • parseInt and parseFloat parse from strings.