Skip to content

Files

Latest commit

 

History

History
22 lines (16 loc) · 616 Bytes

uninvoked-array-callback.md

File metadata and controls

22 lines (16 loc) · 616 Bytes

Pattern: Callback on empty array slots

Issue: -

Description

Using array methods with callbacks on arrays created with new Array(n) won't work as expected. Such arrays contain empty slots rather than actual values, so the callback is never invoked.

Examples

Example of incorrect code:

const items = new Array(3).map(i => i + 1);
const filled = new Array(5).forEach(console.log);

Example of correct code:

const items = Array(3).fill().map(i => i + 1);
const filled = [...Array(5)].forEach(console.log);
const numbers = Array.from({length: 3}, (_, i) => i + 1);