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.