Skip to content

Commit b7ac703

Browse files
committed
Updated info on Math.trunc & Math.floor
1 parent 54240f0 commit b7ac703

File tree

1 file changed

+4
-14
lines changed

1 file changed

+4
-14
lines changed

JavaScript-Quick-Reference.md

+4-14
Original file line numberDiff line numberDiff line change
@@ -2182,21 +2182,11 @@ const randomItem = items[randomIndex];
21822182
console.log(randomItem); // Randomly selected item
21832183
```
21842184

2185-
### Overview of Math.trunc and Math.floor with Math.random
2186-
2187-
**Math.trunc with Math.random:**
2188-
- **Purpose:** Removes the decimal part of a number, leaving the integer.
2189-
- **Use Case:** Ideal for generating random integers from 0 up to (but not including) a maximum value.
2190-
- **Example:** `Math.trunc(Math.random() * 10)` generates integers from 0 to 9.
2191-
2192-
**Math.floor with Math.random:**
2193-
- **Purpose:** Rounds down to the nearest whole number.
2194-
- **Use Case:** Best for generating random integers from 1 to a specified maximum, inclusive.
2195-
- **Example:** `Math.floor(Math.random() * 10) + 1` generates integers from 1 to 10.
2185+
### Math.trunc
2186+
- Math.trunc can be paired with Math.random() for generating zero-based index values, useful in selecting random elements from an array. For example, Math.trunc(Math.random() * array.length) can randomly index into an array, ensuring the index starts at 0 and is within the array bounds.
21962187

2197-
### When to Use Each
2198-
- **Math.trunc:** When you need integers starting at 0. Suitable for zero-based indexes.
2199-
- **Math.floor:** When integers must start from 1. Preferred for inclusive upper-bound ranges.
2188+
### Math.floor
2189+
- Math.floor, on the other hand, can be utilized with Math.random() to create inclusive upper-bound random integers. For instance, Math.floor(Math.random() * (max - min + 1)) + min generates a random integer between min and max, inclusively, catering to situations where the starting integer is 1 and the upper limit must be part of the outcome range.
22002190

22012191
### Advanced Applications
22022192

0 commit comments

Comments
 (0)