Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 612
TCannadySF Avatar asked Jul 16 '26 10:07

TCannadySF


2 Answers

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

like image 118
sherb Avatar answered Jul 17 '26 22:07

sherb


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

like image 30
mattr Avatar answered Jul 18 '26 00:07

mattr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!