Skip to content
Advertisement

Why I cant assign new value for string in array?

In each word from string, every even indexed chars in each word should be upper cased.

Example: “This is a sample” -> “ThIs Is A SaMpLe”

I know that it’s not the best solution to solve this problem but I want to understand why the last assignment doesn’t work.

function toWeirdCase(string) {
const arr = string.toLowerCase().split(' ')

for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr[i].length; j += 2) {
        let temp = arr[i][j]                        // temp = t, i, i

        temp = temp.toUpperCase()                   // temp = T, I, I

        arr[i][j] = temp                           // arr[i][j] = t, i, i but why not T, I, I
    }
}
return arr.join(' ')
}

console.log(toWeirdCase('This is'))

Advertisement

Answer

arr is an array of strings, therefore arr[i] is a string and arr[i][j] = temp attempts to change a character in a string but in JavaScript the strings are immutable.

It is explained in the JavaScript documentation of strings:

When using bracket notation for character access, attempting to delete or assign a value to these properties will not succeed. The properties involved are neither writable nor configurable.

In order to solve your assignment you can build the scrambled value into a new string (let’s name it mixed, by appending one character at a time (mixed = mixed + temp.toUpperCase()) then, in the outer for put mixed back in arr[i]:

const arr = str.toLowerCase().split(' ')

for (let i = 0; i < arr.length; i++) {
    let mixed = '';
    for (let j = 0; j < arr[i].length; j++) {
        let temp = arr[i][j]
        // Turn to uppercase the characters on even positions
        if (j % 2 === 0) {
            temp = temp.toUpperCase()
        }

        mixed = mixed + temp
    }
    // Put the processed word back into the array
    arr[i] = mixed
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement