Search code examples
javascriptfor-loopcapitalizefor-of-loop

how to use for of loop, resulting an array as an output


I want to capitalize the days in the array named 'days' and get the result in an array form only by calling 'console.log(days)'
Please see below : Can anybody help me finish up code in the the block of for of loop?

edit(summary) : I questioned this to know the reason why the value of the each 'day' does not get changed in this case. and Suren Srapyan has provided a great answer to this : 'You are getting the copy of each item in the loop. So day is only a copy of the item's value and changing it to have another value will not change the item in the array.'

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

for (day of days) {
    day = day[0].toUpperCase() + day.slice(1);
    // your code goes here

}
console.log(days);

Solution

  • for of is not like to any simple loop. Under it is another construction.

    You are getting the copy of each item in the loop. So day is only a copy of the item's value and changing it to have another value will not change the item in the array.

    Here is what going under the for of loop.

    let days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
    
    const iterator = days[Symbol.iterator]();
    let item = iterator.next();
    
    while(!item.done) {
        console.log(item.value);
        item = iterator.next();
    }

    Above code shows that for of loop is only for readonly purposes

    You can use Array#map function for it

    let days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
    
    days = days.map(day => day[0].toUpperCase() + day.slice(1));
    
    console.log(days);