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?

3 Answers 3

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');
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

5 Comments

a change made to the object through one reference will be visible through all other references Not true. Check out this fiddle: jsfiddle.net/JdW6m
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
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.
I quote strings are immutable objects the important part there is objects

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.