Just Enough Numbers

JavaScript’s Primary Numeric Type: Number

JavaScript’s primary numeric type is Number, which is versatile enough to handle both integers and approximate real numbers. This flexibility is key to many operations in JavaScript, making Number one of the most commonly used data types. JavaScript supports numeric literals in several formats. For instance, a base-10 integer in JavaScript is simply written as a sequence of digits, such as 0, 5, or 50000000.

Numeric Literals Beyond Base-10

But JavaScript doesn’t stop at base-10; it also recognizes hexadecimal values, which are base-16. In this format, a digit can be anything from 0 to 9 or the letters a (or A) through f (or F), representing values from 10 to 15. For example, 0x1A would represent the decimal value 26. Starting with ES6, JavaScript introduced even more numeric formats: you can now write integers in binary (base-2) or octal (base-8) using the prefixes 0b and 0o respectively, such as 0b1010 for 10 in decimal or 0o12 for 10 in decimal.

// Hexadecimal (base-16)
let hexValue1 = 0x1a; // 26 in decimal
let hexValue2 = 0xff; // 255 in decimal

console.log(hexValue1); // Output: 26
console.log(hexValue2); // Output: 255

// Binary (base-2) - Introduced in ES6
let binaryValue1 = 0b1010; // 10 in decimal
let binaryValue2 = 0b1101; // 13 in decimal

console.log(binaryValue1); // Output: 10
console.log(binaryValue2); // Output: 13

// Octal (base-8) - Introduced in ES6
let octalValue1 = 0o12; // 10 in decimal
let octalValue2 = 0o77; // 63 in decimal

console.log(octalValue1); // Output: 10
console.log(octalValue2); // Output: 63

Floating-Point Numbers and Exponential Notation

When dealing with real numbers, JavaScript allows you to use floating-point literals, which can include a decimal point. For example, 3.14 is a floating-point literal. JavaScript also supports exponential notation for representing real numbers, where you can follow a number with e (or E) and an exponent, like 1.23e4, which equates to 1.23 * 10^4.

// Floating-point literals
let float1 = 3.14; // A simple floating-point number
let float2 = -0.001; // A negative floating-point number
let float3 = 2.0; // A floating-point number with a zero decimal

console.log(float1); // Output: 3.14
console.log(float2); // Output: -0.001
console.log(float3); // Output: 2

// Exponential notation
let exp1 = 1.23e4; // 1.23 * 10^4 (equivalent to 12300)
let exp2 = 5.67e-3; // 5.67 * 10^-3 (equivalent to 0.00567)
let exp3 = 9.81e2; // 9.81 * 10^2 (equivalent to 981)

console.log(exp1); // Output: 12300
console.log(exp2); // Output: 0.00567
console.log(exp3); // Output: 981

Enhancing Readability with Numeric Separators

To make long numeric literals more readable, you can use underscores as separators. For instance, instead of writing 1000000, you could write 1_000_000 to break it up into more digestible chunks.

// Numeric literals with underscores
let million = 1_000_000; // One million
let largeNumber = 123_456_789; // A large number

// Floating-point literals with underscores
let largeFloat = 1_234.567_890; // A large floating-point number

console.log(million); // Output: 1000000
console.log(largeNumber); // Output: 123456789
console.log(largeFloat); // Output: 1234.56789

Arithmetic Operations and Mathematical Functions

Arithmetic in JavaScript is straightforward, with the basic operators + for addition, - for subtraction, * for multiplication, / for division, and % for modulo (which gives the remainder of a division). ES2016 added the ``operator for exponentiation, making it easier to perform power calculations like23for2^3. For more complex mathematical operations, JavaScript provides a range of functions and constants through the Mathobject, such asMath.sqrt()for square roots andMath.PI for the value of π.

// Basic arithmetic operations
let addition = 5 + 3; // Addition: 8
let subtraction = 10 - 4; // Subtraction: 6
let multiplication = 7 * 6; // Multiplication: 42
let division = 20 / 4; // Division: 5
let modulo = 29 % 5; // Modulo (remainder): 4

console.log(addition); // Output: 8
console.log(subtraction); // Output: 6
console.log(multiplication); // Output: 42
console.log(division); // Output: 5
console.log(modulo); // Output: 4

// Exponentiation operator (introduced in ES2016)
let exponentiation = 2 ** 3; // 2 raised to the power of 3 (8)

console.log(exponentiation); // Output: 8

// Using the Math object for complex operations
let squareRoot = Math.sqrt(16); // Square root of 16 (4)
let piValue = Math.PI; // Value of π (3.141592653589793)

console.log(squareRoot); // Output: 4
console.log(piValue); // Output: 3.141592653589793

Special Numeric Values: Infinity and NaN

JavaScript also defines global constants like Infinity and NaN (Not-a-Number). Infinity represents values that exceed the largest representable number, while NaN signifies an invalid number. The global function isNaN() helps identify if a value is NaN or if it’s a non-numeric value that can’t be converted to a number, similar to Number.isNaN().

// Global constants
let largeNumber = 1 / 0; // Infinity
let invalidNumber = "abc" * 2; // NaN (Not-a-Number)

console.log(largeNumber); // Output: Infinity
console.log(invalidNumber); // Output: NaN

// Checking for NaN using isNaN()
console.log(isNaN(largeNumber)); // Output: false (Infinity is not NaN)
console.log(isNaN(invalidNumber)); // Output: true (NaN is NaN)
console.log(isNaN("123")); // Output: false ('123' can be converted to number 123)
console.log(isNaN("abc")); // Output: true ('abc' cannot be converted to a number)

// Checking for NaN using Number.isNaN()
console.log(Number.isNaN(largeNumber)); // Output: false (Infinity is not NaN)
console.log(Number.isNaN(invalidNumber)); // Output: true (NaN is NaN)
console.log(Number.isNaN("123")); // Output: false (Number('123') is not NaN)
console.log(Number.isNaN("abc")); // Output: false (Number('abc') is NaN but not of type number)

// Additional example of NaN
let result = Math.sqrt(-1); // NaN (Square root of a negative number is not a real number)
console.log(result); // Output: NaN

Working with Large Integers: BigInt

For those times when regular Number types just won’t cut it—like when you need to represent extremely large integers—JavaScript introduced the BigInt type in ES2020. BigInt allows for integers of arbitrary precision, meaning you can work with numbers far beyond the limits of Number. You can create a BigInt by appending an n to the end of an integer literal, like 12345678901234567890n. Additionally, you can use the BigInt() function to convert regular numbers or strings to BigInt values.

// Creating BigInt values
let bigInt1 = 12345678901234567890n; // Using the 'n' suffix to create a BigInt literal
let bigInt2 = BigInt("12345678901234567890"); // Using the BigInt() function to convert a string

console.log(bigInt1); // Output: 12345678901234567890n
console.log(bigInt2); // Output: 12345678901234567890n

The Power and Flexibility of JavaScript Numbers

These features make JavaScript's handling of numbers both powerful and flexible, providing you with the tools you need to perform a wide range of numerical operations. Whether you're dealing with simple integers, complex floating-point numbers, or massive integers that require BigInt, JavaScript has you covered.

Mastering JavaScript's Numeric Fundamentals

We've covered a solid foundation on numbers, giving you more than enough to get started writing applications with confidence. All the essentials are here, and they’ll serve you well in 95% of the scenarios you’ll encounter. There’s plenty more to learn, but we’ve intentionally kept things streamlined at this stage of your journey, as you earn your blue belt in JavaScript. More advanced topics like overflow, underflow, division by zero, negative zero values, and binary floating-point rounding errors will come later when you're ready to level up on more advanced belts. For now, focus on mastering these fundamentals—they’ll be your go-to tools as you continue to grow as a developer.

Study Style Notes

JavaScript's Numeric Types

  • Primary Numeric Type: Number
    • Handles both integers and approximate real numbers.
    • Versatile for many operations in JavaScript.
    • Commonly used data type.

Numeric Literals in JavaScript

  • Base-10 Integer Literals: Written as a sequence of digits (e.g., 0, 5, 50000000).
  • Hexadecimal Values (Base-16):
    • Uses digits 0-9 and letters A-F (or a-f).
    • Example: 0x1A represents 26 in decimal.
  • Binary (Base-2) and Octal (Base-8) Literals:
    • Introduced in ES6.
    • Use prefixes 0b (binary) and 0o (octal).
    • Examples: 0b1010 (binary for 10), 0o12 (octal for 10).

Real Numbers and Exponential Notation

  • Floating-Point Literals: Include a decimal point (e.g., 3.14).
  • Exponential Notation: Use e or E followed by an exponent (e.g., 1.23e4 equals 1.23 * 10^4).

Numeric Separators for Readability

  • Underscores: Used to separate digits in long numeric literals.
    • Example: 1_000_000 instead of 1000000.

Arithmetic Operations in JavaScript

  • Basic Operators:
    • + (addition), - (subtraction), * (multiplication), / (division), % (modulo).
  • **Exponentiation Operator (**):**
    • Introduced in ES2016 for power calculations (e.g., 2**3 equals 2^3).
  • Math Object:
    • Provides functions like Math.sqrt() for square roots.
    • Constants like Math.PI for π.

Special Numeric Values

  • Infinity: Represents values beyond the largest representable number.
  • NaN (Not-a-Number): Represents an invalid number.
    • Functions:
      • isNaN(): Checks if a value is NaN or not numeric.
      • Number.isNaN(): More precise for determining NaN.

BigInt: Handling Large Integers

  • BigInt Type: Introduced in ES2020.
    • Represents integers of arbitrary precision.
    • Created by appending n to an integer literal (e.g., 12345678901234567890n).
    • Can also use BigInt() to convert numbers or strings to BigInt.

JavaScript's Numeric Capabilities

  • Flexible and Powerful: Handles a wide range of numeric operations.
    • Supports:
      • Simple integers.
      • Complex floating-point numbers.
      • Massive integers (using BigInt).

Mastering JavaScript Numbers

  • Foundational Knowledge: Essential for developing applications confidently.
  • Future Learning:
    • Advanced topics: overflow, underflow, division by zero, negative zero, and binary floating-point rounding errors.
    • Focus on mastering fundamentals first for effective growth as a developer.