Math.floor()
ES1+Returns the largest integer less than or equal to a given number.
Syntax
Math.floor(x)Parameters
x number A number
Return Value
The largest integer less than or equal to the given number
Examples
console.log(Math.floor(4.7));
console.log(Math.floor(4.2));
console.log(Math.floor(-4.7)); 📌 When to Use
Use Math.floor() for pagination calculations, array indexing from decimal values, or when you need to round down to allocate whole units (like items per page).
⚠️ Common Mistakes
Not realizing Math.floor() rounds toward negative infinity for negative numbers (-4.7 becomes -5, not -4).
Using Math.floor() when Math.trunc() is more appropriate for simply removing decimals.
✅ Best Practices
Use Math.floor() with Math.random() to generate random integers: Math.floor(Math.random() * max).
For negative numbers where you want to truncate toward zero, use Math.trunc() instead.
⚡ Performance Notes
Math.floor() is optimized by JavaScript engines. The bitwise alternative (x | 0) is faster but only works for 32-bit integers and truncates rather than floors negative numbers.
🌍 Real World Example
Pagination Calculator
Calculate total pages needed for a list of items with a given page size.
function calculatePagination(totalItems, itemsPerPage) {
const totalPages = Math.ceil(totalItems / itemsPerPage);
const currentPage = 1;
const startIndex = Math.floor((currentPage - 1) * itemsPerPage);
return {
totalPages,
startIndex,
endIndex: Math.min(startIndex + itemsPerPage, totalItems)
};
}
console.log(calculatePagination(95, 10));
// { totalPages: 10, startIndex: 0, endIndex: 10 }