5 of 17 menu

The Error of Modifying an Array Element in JavaScript

Let's consider an error that occurs when incorrectly modifying an array element. Suppose we are given the following array:

let arr = [1, 2, 3, 4, 5];

Suppose we also have a function that takes a number as a parameter and returns the square of that number:

function func(num) { return num ** 2; }

Let's use a for-of loop to iterate through our array and apply our function to each of its elements:

for (let elem of arr) { elem = func(elem); }

This is where beginners often make a mistake. The fact is that changing the elem variable does not lead to a change in the element in the array itself. Let's verify this:

console.log(arr); // the array has not changed

The array does not change because the elem variable contains a copy of the element, not a reference to it. Changing elem affects the copy, but not the array itself.

To solve the problem, you need to modify the array elements themselves:

for (let i = 0; i < arr.length; i++) { arr[i] = func(arr[i]); } console.log(arr); // now the array has changed
English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline