0

I want to add prototype function in string object. I working with it but it is not uppercase the string value. Fiddle

String.prototype.myUcase=function()
{
 return this.toUpperCase();
}
4
  • You don't assign the return value of myUcase to a variable, you simply ignore it. toUpperCase doesn't modify the string itself, it returns a new string. Commented Oct 12, 2013 at 5:34
  • fruits = fruits.myUcase() Commented Oct 12, 2013 at 5:34
  • jsfiddle.net/efEzN/4. I have updated your fiddle Commented Oct 12, 2013 at 5:42
  • Why need to assign function in fruits Commented Oct 12, 2013 at 5:51

1 Answer 1

1

In javascript String is not mutable. So, when you do this.toUpperCase() it does not change the current string. Instead, it creates a new string with the uppercased letters in it.

If you want your example to work, you can do (as suggested by elclanrs in the comments)

fruits = fruits.myUcase();
Sign up to request clarification or add additional context in comments.

2 Comments

But with Array prototype it is returning value. w3schools.com/js/tryit.asp?filename=tryjs_prototype_array
@amit Correct. That is because, javascript Arrays are basically objects and so they are mutable by default. this[i]=this[i].toUpperCase(); this particular line, modifies each and every element. That is why you are able to see the result.

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.