TCannadySF
TCannadySF

Reputation: 286

Calling toUppercase() on a string variable

I'm a beginner and just successfully trouble-shoot my code. I'm glad that I found it, however it took me a long time. I'm hoping to learn why it happened.

Here's the buggy original code. Assume that the variable [nextAlpha] has already been assigned a string value:

nextAlpha.toUpperCase();

Through some creative testing I was able to determine it was the line causing issues. I thought perhaps it's not actually updating the value of variable [nextAlpha]. I tried this instead, and it worked:

nextAlpha = nextAlpha.toUpperCase();

I've left the rest of my code out, but assume that [var = nextAlpha] has already been declared at the top of my script, which I think means "globally." With that information, I thought it was enough to simply call the method on the variable. Why doesn't this "update" the string to upper case like it does when I go the extra step to (re)assign it to the original [nextAlpha] string?

Upvotes: 3

Views: 1583

Answers (3)

mattr
mattr

Reputation: 5518

In JavaScript, Strings are immutable:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures

Unlike in languages like C, JavaScript strings are immutable. This means that once a string is created, it is not possible to modify it. However, it is still possible to create another string based on an operation on the original string

Upvotes: 2

toUpperCase() is a function (so return a value) not a property (affect the variable itself)

Upvotes: 1

sherb
sherb

Reputation: 6095

toUpperCase returns the converted string as a new object - it does not perform the conversion on nextAlpha.

From the Mozilla reference:

The toUpperCase method returns the value of the string converted to uppercase. toUpperCase does not affect the value of the string itself.

reference

Upvotes: 2

Related Questions