Explain Codes LogoExplain Codes Logo

Change values in array when doing foreach

javascript
prompt-engineering
functions
callbacks
Nikita BarsukovbyNikita Barsukov·Dec 11, 2024
TLDR
// Use forEach() to wield your wizardly powers and alter array element values using their index: let numbers = [1, 2, 3]; numbers.forEach((num, idx) => numbers[idx] *= 2); // Boom! Now numbers is [2, 4, 6]

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:

let numbers = [1, 2, 3]; numbers.forEach((value, index, array) => { // Like a wizard casting a spell to double the numbers array[index] = value * 2; });

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! 🧙‍♂️

let users = [{ name: 'Alice' }, { name: 'Bob' }]; users.forEach(user => user.name += " Smith"); // Poof! Now users is [{ name: 'Alice Smith' }, { name: 'Bob Smith' }]

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.

function logUpperCase() { // `this` refers to the passed context object console.log(this.toUpperCase()); } ["a", "b", "c"].forEach(logUpperCase, String.prototype);

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:

let doubled = numbers.map(num => num * 2);

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:

let evens = numbers.filter(num => num % 2 === 0);

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:

let arrWithHoles = [1, , 3]; arrWithHoles.forEach((num) => console.log(num)); // like a secret agent, it only logs 1 and 3

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!