2 Math basics for JavaScript

 

This chapter covers

  • JavaScript’s arithmetic and comparison operators
  • JavaScript number types and precision issues
  • Working with really large integers
  • Rounding numbers in JavaScript
  • Generating random numbers

JavaScript is chock full of numbers. Whether your code calculates element dimensions, animates transitions, works with dates or financial data, or just loops through an array, the numbers are there, sometimes right out in the open, other times lurking in the shadows. When it comes to doing math with JavaScript, the good news is that JavaScript makes it easy to work with numbers; the bad news is that those numbers don’t always behave the way you might expect. The goal of this chapter is to meet you at those expectations and show you how to adjust them so that when you do math with JavaScript you don’t end up pulling out all your hair in frustration. To that end, this chapter helps you build a rock-solid understanding of how JavaScript handles numbers behind the scenes, so you can write code that’s more accurate, reliable, and bug-free.

2.1 Building JavaScript expressions

Most of your JavaScript math career will involve building expressions, which are combinations of operands (expression input values such as numbers, variables, object property values, or method or function results) and operators (symbols that specify the action you want JavaScript to perform on one or more of the operands) that return a value.

2.1.1 JavaScript arithmetic operators

2.1.2 JavaScript arithmetic assignment operators

2.1.3 JavaScript comparison operators

2.1.4 JavaScript logical expressions

2.1.5 Falsy values, default values, and nullish coalescing

2.1.6 Operator precedence

2.1.7 Using parentheses to avoid ambiguity

2.2 Number types in JavaScript

2.2.1 Integer and floating-point numbers

2.2.2 Exponential notation

2.2.3 Binary, octal, and hexadecimal representations

2.2.4 NaN and Infinity in JavaScript

2.2.5 NaN

2.2.6 Infinity and -Infinity

2.2.7 Number coercion

2.3 Precision issues and floating-point arithmetic

2.3.1 Why 0.1 + 0.2 !== 0.3

2.3.2 When to be concerned about precision

2.4 Working with BigInt values

2.4.1 BigInt to the rescue

2.4.2 Mathematical operations with BigInt

2.4.3 Limitations of BigInt in JavaScript

2.4.4 When to avoid BigInt in web development

2.5 Modulo logic and wrapping values

2.5.1 JavaScript’s remainder operator (%) and modulo

2.5.2 Wrapping logic in carousels, sliders, and cyclic UI

2.6 Rounding numbers

2.6.1 Rounding to whole numbers

2.6.2 Rounding to a specific number of decimal places

2.6.3 Implementing bankers’ rounding

2.6.4 Use cases for rounding in front-end development

2.7 Generating random numbers