Change values in array when doing foreach
Applying forEach to modify arrays
JavaScript's forEach()
works like a charm for many diverse scenarios—be it invoking side effects or tweaking the original array. Let's sequentially unwrap the situations where forEach()
acts like a superhero.
Modifying primitives directly
forEach()
allows in-place modifications of the elements of an array using an index, making it the go-to tool when wrestling with primitive values - it's like your swiss army knife in a wild desert:
Changing objects in array
When dealing with object arrays, modification is by reference, letting you change properties directly without the need to acccess the array by index. It's like direct telepathy! 🧙♂️
Inserting 'this' in forEach
Need a specific context (this
) for your forEach
callback? Provide it as the second argument. Note: Arrow functions do not bow down to this rule; they maintain their distances from this
.
Preserving the original array
In JavaScript, changing arrays, particularly their immutable nature, can lead to unexpected states. To preserve the original array when modifying it, utilize methods that create new arrays.
The Map magician
map()
conjures a new array from an existing one by casting a function on each element, leaving no scars on the original:
Filtering the unneeded
Want to pluck out specific items based on a condition? filter()
is your guardian angel that delivers an untouched, purified subset of your array:
More non-altering spells
some
, every
, and find
are your other allies for any magic trick that requires the original array to stay pristine.
Dodging the traps
Manipulating array data with forEach
can sometimes be as tricky as disarming a bomb. Here are some landmines to steer clear of:
Overlooking emptiness
forEach()
seems to have an aloof nature towards empty slots in arrays, it tends to give them the cold shoulder:
Meddling with array length
Tinkering with the length of an array while in a forEach
feels similar to trying to change shoes while running—it leads to unforeseen complications!
Misleading indexes
Modifying elements at specific indexes during iteration doesn't affect the current index—even if items were removed or added beforehand. A sly trickster, indeed!
Was this article helpful?