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
It seems a misconception is at the base of your question: assigning to the loop variable of a
for...ofloop 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 arraydays. There is no "memory" inindexthat knows that it got its value from thedaysarray --indexis 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 thisindexvariable.In the old-school
forloop the corresponding assignment is todays[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..ofloop is not the right tool if you want to mutate an array. As alternative you could use.mapand assign the resulting (new!) array back todays:*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
varvariables in a browser context are aliases forwindowproperties, and in sloppy mode the elements of theargumentsarray are aliases for the individual function arguments. But none of those exceptions apply here.