This code does not work
var x ='hello';
x[2] ='a';
Why doesn't it work? I am not using the replace() function
This code does not work
var x ='hello';
x[2] ='a';
Why doesn't it work? I am not using the replace() function
In javascript the strings are immutable, you cannot change the string using index. The string manipulation methods such as trim, slice return new strings.
It doesn't work because of legacy behavior of promoting string
values to String
object wrappers with the value of the primitive string
value.
So for example
"xyz".charAt(0)
is at least notionally evaluated as
(new String("xyz")).charAt(0)
because charAt
is a prototype method of String
objects and can be applied to a primitive string value in this manner.
The down side is that the promoted String object is never stored anywhere and, even if modified in JavaScript is immediately discarded. This is what is happening in the code posted:
var x ='hello';
x[2] ='a';
is treated as
new String(x)[2] = 'a'
followed by discarding the String object which, incidentally, has a property named 2
with value 'a'
.
The general solution to this is to run JavaScript in strict mode, so that any attempt to assign a property to a primitive value which has been promoted to an object wrapper generates an error:
"use strict"
var x ='hello';
x[2] ='a';