1
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?

rat
  • 143
  • 1
  • 7

3 Answers3

3

Strings are immutable. You cannot change them. You have to create a new string for that.

function cun(str) {
    var newString = 'z' + str.substring(1);
    console.log( newString[0] );
    return newString;
}

cun('ratul');
Joe Simmons
  • 1,828
  • 2
  • 12
  • 9
2

Because strings are immutable (meaning you can't change their value) in JavaScript.

You can accomplish what you are trying to do a variety of ways, including:

var cun = function(cun){
    return "z" + cun.slice(1);
}
cun("ratul");
go-oleg
  • 19,272
  • 3
  • 43
  • 44
0

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"));

Here is working Demo

Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
  • `a change made to the object through one reference will be visible through all other references` Not true. Check out this fiddle: http://jsfiddle.net/JdW6m/ – Joe Simmons Oct 02 '13 at 06:50
  • but I never say it will change..... :( last sentence is `however, you can have multiple references to a string object and not worry that the string value will change without your knowing it` – Zaheer Ahmed Oct 02 '13 at 07:56
  • Look at my fiddle. `a` 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. – Joe Simmons Oct 02 '13 at 09:30
  • I quote `strings are immutable objects` the important part there is **objects** – Joe Simmons Oct 02 '13 at 09:54
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/38476/discussion-between-zaheer-ahmed-and-joe-simmons) – Zaheer Ahmed Oct 02 '13 at 09:57