Number and Math
- Node.js course
- Beginner
- Lesson 15/116
- 4 min
Learn Number methods and the Math object.
Number and Math
In JavaScript, all numbers are of type number; there is no separate integer and decimal type. The Math object provides ready-made functions for common math operations.
For example, Math.max(3, 9, 5) returns the largest value; Math.min(3, 9, 5) the smallest. Math.floor(3.7) rounds down, Math.ceil(3.2) rounds up.
Math.round(3.5) rounds to the nearest integer. These functions make number operations easy.
Number conversions
To convert a string to a number, you use the Number(...) function. For example, Number('42') returns the number 42.
If the string does not look like a number, the result is NaN (Not-a-Number). For example, Number('hello') returns NaN.
This is very useful when converting user input to numbers, especially from command-line arguments.
Practice Find the largest with Math.max
Declare three numbers: a = 12, b = 45, c = 7. Find the largest with Math.max(a, b, c) and print it with console.log.
Starter code
const a = 12;
const b = 45;
const c = 7;
// Find the largest with Math.max and log itSample solution
const a = 12;
const b = 45;
const c = 7;
console.log(Math.max(a, b, c));Expected output
45
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Using Math.max
const largest = Math.max(3, ____);
const largest = Math.max(3, 9);
Explanation: Math.max returns the largest number.
2 Match the Math functions
| Term | Meaning |
|---|---|
Math.max |
Largest |
Math.min |
Smallest |
Math.floor |
Round down |
Math.round |
Nearest integer |
3 What does Number("42") return?
- The string '42'
- Throws an error
- undefined
- The number 42 Correct answer
Explanation: Number('42') returns the number 42.