Calling toUppercase () on a string variable

I am a newbie and am just getting through my code successfully. I'm glad I found this, but it took me a long time. I hope to find out why this happened.

Here is the source code for the buggy. Let's assume the variable [nextAlpha]

has already been assigned a string value:

nextAlpha.toUpperCase();

      

Through some creative testing, I was able to determine that it was the problem causing the problems. I thought it might not be updating the value of the variable [nextAlpha]

. I tried this instead and it worked:

nextAlpha = nextAlpha.toUpperCase();

      

I've left the rest of my code behind, but let's say it's [var = nextAlpha]

already declared at the top of my script, which I think means "globally". With this information, I thought it would be enough to just call a method on a variable. Why is it "updating" the uppercase string, as it does when I go to the extra step to (re) assign it to the original string [nextAlpha]

?

+3


source to share


3 answers


toUpperCase

returns the converted string as a new object - it does not convert to nextAlpha

.

From Mozilla link:



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

reference

+2


source


In JavaScript, strings are immutable:

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



Unlike C languages, JavaScript strings are immutable. This means that once a row is created, it cannot be changed. However, you can still create another string based on the operation on the original string

+2


source


toUpperCase()

is a function (so return a value), not a property (affects the variables themselves)

+1


source







All Articles