title, shortTitle, type, language, tags, author, cover, excerpt, dateModified
| title |
shortTitle |
type |
language |
tags |
author |
cover |
excerpt |
dateModified |
| Code Anatomy - For loops, array reduce and method chaining |
For loops, array reduce and method chaining |
story |
javascript |
|
chalarangelo |
case-study |
There are many ways to iterate and transform array data in JavaScript. Learn how each one works and where you should use them. |
2021-06-12T19:30:41+03:00 |
For loops
- Any
for loop can be used - read more about the different JavaScript loops.
- Less common nowadays, due to functional programming being more popular.
- Control over the iteration, such as skipping over elements or early
returns.
- Resulting array needs to be declared beforehand, outside the loop.
- Uses
Array.prototype.push() or the spread (...) operator to add elements.
O(N) complexity, each element will be iterated over only once.
Array reduce
- Uses
Array.prototype.reduce() with an empty array as the initial value.
- More common nowadays, due to functional programming being more popular.
- Less control over the iteration, cannot skip elements or
return early.
- Can be chained with other methods, if necessary.
- Uses
Array.prototype.push() or the spread (...) operator to add elements.
O(N) complexity, each element will be iterated over only once.
Method chaining
- Uses
Array.prototype.map() and Array.prototype.filter().
- More common nowadays, due to functional programming being more popular.
- Less control over the iteration, cannot skip elements or
return early.
- Declarative, easier to read and refactor, chain can grow as necessary.
- Does not use
Array.prototype.push() or the spread (...) operator.
O(cN) complexity, c iterations per element, (c: length of the chain).