Home > Software engineering >  issue with the result of javascript for of loop code
issue with the result of javascript for of loop code

Time:11-23

i tried a code to upper case each letter at the beginning of a word on an array of strings both by traditional for loop and for of loop but it didn't work with the for of loop.

let days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];

/*for (var index = 0 ; index < days.length ; index  )
{
let test = Array.from(days[index]);
//console.log(test);
let x = days[index].charCodeAt(0)-32;
//console.log(x);
test[0] = String.fromCharCode(x);
//console.log(test);
days[index] = test.join("");
}*/



for (let index of days)
{
    //console.log(index);
    let test = Array.from(index);
    //console.log(test);
    let x = index.charCodeAt(0)-32;
    //console.log(x);
    test[0] = String.fromCharCode(x);
    //console.log(test);
    index = test.join("");
}
console.log(days);

the upper loop worked perfectely but the lower one didn't

CodePudding user response:

It seems a misconception is at the base of your question: assigning to the loop variable of a for...of loop will not modify the array you are looping over. An assignment to a variable is just that: the variable changes -- not the array where that variable initially got a value from.

So in your case, index = test.join(""); will not change anything to the array days. There is no "memory" in index that knows that it got its value from the days array -- index is just a variable like any other. Once you realise this, it also becomes clear that this assignment achieves nothing useful, as nothing more happens with this index variable.

In the old-school for loop the corresponding assignment is to days[i]. That is not an assignment to a variable, but to a property! That is a whole different story. Assigning to a property will mutate the object that owns that property. In this case that object is an array, and the property is an index. Assigning to a variable does not change a data structure.*

A for..of loop is not the right tool if you want to mutate an array. As alternative you could use .map and assign the resulting (new!) array back to days:

let days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];

days = days.map(day => day[0].toUpperCase()   day.slice(1));

console.log(days);


*Assigning to a variable does not change a data structure.: There are some exceptions to this rule when variables are true aliases for properties, like the global var variables in a browser context are aliases for window properties, and in sloppy mode the elements of the arguments array are aliases for the individual function arguments. But none of those exceptions apply here.

  • Related