The Number data type in JavaScript does exactly what you expect! It is used to represent any numerical value, including integers and decimal numbers. As one of your first data types, you'll be interested in what operations you can use with numbers.
JavaScript's Number encompasses numerical values. All of the following values are examples of the number type:
42;
-5;
3.14159;
7.0;
For any given data type, you should familiarize yourself with the operations that you can perform with that type. The word operator refers to the symbol that performs a particular operation. For example, the + operator performs the addition operation. Here are the common arithmetic operators in JS:
With number values and arithmetic operators in hand, you can use them to evaluate your first expressions:
console.log(2 + 3); // => 5
console.log(42 - 42); // => 0
console.log(-4 * 1.5); // => -6
console.log(25 / 8); // => 3.125
Nothing too groundbreaking about the results above. An expression consists of values and operators. JavaScript will evaluate an expression into a single value.
You can write more complex expressions using multiple operators. However, you'll want to be aware of the general math order of operations (do you remember the acronym PEMDAS - Parentheses, Exponents, Multiplication, Division, Addition, and Subtraction?) You execute anything in parentheses first, then perform exponents, then multiplication-division operations, and finally addition-subtraction operations:
console.log(5 * 3 + 2); // => 15 + 2 = 17
console.log(2 + 3 * 5); // => 2 + 15 = 17
console.log((2 + 3) * 5); // => 5 * 5 = 25
All of the math operators listed above are the simple operations you use everyday, except for maybe modulo %. Modulo gives you the remainder that results from a division. For example, 10 % 3 is 1 because when you divide 10 by 3, you are left with a remainder of 1 (10 / 3 = 9 1/3). You can read 10 % 3 as "ten modulo three" or "ten mod three."
console.log(10 % 3); // => 1
console.log(14 % 5); // => 4
console.log(20 % 17); // => 3
console.log(18 % 6); // => 0
console.log(7 % 9); // => 7
Modulo is a very useful operation in the realm of computers. You can use it to check the divisibility of numbers, whether numbers are even, whether they are prime, and much, much more. Don't take this seemingly simple operation for granted! You'll provide a ton of practice using these modulo patterns as you move through the course.
In the order of operations, modulo has the same precedence as multiplication-division. So your complete order of math operations in JS is parentheses, multiplication-division-modulo, addition-subtraction.
// modulo has precedence over addition
console.log(4 + 12 % 5); // => 6
console.log((4 + 12) % 5); // => 1