2

I am testing immutability of a string and wrote this function that takes in a String.

Since a string is immutable, str[i] below, cannot be assigned to any value.

However, when I run this function, it does not give me an error. Why is that? (as per my study, I believe this line (str[i] ='x' should break the system/stop executing the function and throw an error. But it does not (this is written in VSCode editor)

function tuc(str) {
        let res = [];
        for (let i = 0; i < str.length; i++) {
            str[i]='x';
            let c = str[i];
            res.push(c.toUpperCase());
        }
        return res.join("");
    }
Snowcat
  • 470
  • 8
  • 16

1 Answers1

4

The expression

    str[i] = 'x';

implicitly creates a String instance from the string primitive. The property is set on that object, but the object isn't saved anywhere. Setting the property on the String instance does not affect the primitive string value of str.

So in other words

    str[i] = 'x';

is effectively the same as

    (new String(str))[i] = 'x';

Because that transient object does successfully get a new property from the assignment, there is no exception to throw.

Note that the construction of an implicit String instance is not a special case in this particular code; even something like

    var len = str.length;

creates a transient String instance. (Of course a modern JavaScript runtime can generally recognize that it doesn't really need a String instance, but that's the concept involved.)

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 2
    **Additional note for OP**: It errors as expected if using [strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode) – BCDeWitt Oct 14 '19 at 22:34
  • Thanks that is helpful. When I console.log it, it loops through and logs x, makes sense as it is the Instance value. btw, I have Strict Mode on but that did not provide an error – Snowcat Oct 15 '19 at 17:39