var cun = function(cun){
cun[0] = 'z';
console.log(cun[0]);
return cun;
}
cun("ratul");
Why it is print r on console but not z ? why i can't change the string using array notation?
from the rhino book:
In JavaScript, strings are immutable objects, which means that the characters within them may not be changed and that any operations on strings actually create new strings. Strings are assigned by reference, not by value. In general, when an object is assigned by reference, a change made to the object through one reference will be visible through all other references to the object. Because strings cannot be changed, however, you can have multiple references to a string object and not worry that the string value will change without your knowing it
You can try:
String.prototype.replaceAt=function(index, character) {
return this.substr(0, index) + character + this.substr(index+character.length);
}
var hello="ratul";
alert(hello.replaceAt(0, "z"));
a change made to the object through one reference will be visible through all other references Not true. Check out this fiddle: jsfiddle.net/JdW6mhowever, you can have multiple references to a string object and not worry that the string value will change without your knowing ita was 'hello' and b was set to a I changed a, so b should change as well, according to your quote, but it doesn't.strings are immutable objects the important part there is objects