Polyfilling Array.prototype.flat with core-js: A Decision Guide for Legacy Environments
Use core-js 3.23+ to polyfill Array.prototype.flat for deep array flattening in legacy JavaScript. Supports depth control, adds ~1.2 KB gzipped, handles sparse arrays as undefined.
26 Jul 2026, 20:45 UTC

The Problem: Deep Array Flattening in Legacy JavaScript
You need to flatten nested arrays to depth greater than 1 in a JavaScript environment that lacks Array.prototype.flat support (ES2019). Using native .flat() throws a TypeError in IE 11 or Node < 11.
Decision: Use core-js Polyfill
Choose core-js version 3.23.0 or later to polyfill Array.prototype.flat. This ensures consistent behavior across ES5+ environments without manual implementation.
Supported Options Compared
| Approach | Browser Support | Bundle Impact | Depth Control | Sparse Array Handling |
|---|---|---|---|---|
core-js es/array.flat | IE 11+, Node 6+ | ~1.2 KB gzipped | Yes (default 1) | Holes become undefined |
| Manual recursive function | All | 0 KB (inline) | Yes | Preserves holes |
lodash flattenDeep | All | ~2.5 KB gzipped | Depth 1 only | Preserves holes |
Trade-offs
core-js vs manual: core-js adds a small bundle cost but guarantees spec compliance. Manual functions are zero-cost but risk edge cases like sparse arrays.
core-js vs lodash: core-js is lighter and supports configurable depth. lodash offers more utilities but increases bundle size.
Implementation
Install and import in your entry file:
# Run in project root with write permissions
npm install core-js@3.23.0 --save
# In your application entry (e.g., index.js):
import 'core-js/es/array/flat';n
# Usage:
const nested = [1, [2, [3, [4, 5]]]];
const flatOne = nested.flat(); // [1, 2, [3, [4, 5]]]
const flatDeep = nested.flat(Infinity); // [1, 2, 3, 4, 5]
// Verify polyfill loaded:
console.log('flat available:', typeof Array.prototype.flat === 'function');
Verification Steps
- Check version:
node -e "console.log(require('core-js/package.json').version)"(must show 3.23.0+) - Test in target environment:
node --no-warnings -e "[1,[2,[3]]].flat(2)" 2>/dev/null || echo "Polyfill required" - Confirm output:
[1, [2, [3, 4]]].flat(2)should return[1, 2, 3, 4]
Limitations
The polyfill converts sparse array holes to undefined, unlike native behavior in some engines. Test with arrays containing [, , 3] if sparsity matters.
Rollback
If issues arise, remove the import and replace calls with a manual flatten function or switch to lodash. No state changes persist beyond the import statement.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.