JavaScript JavaScript and the DOM Responding to User Interaction Listening for Events with addEventListener()

Why doesn't the method "toUpperCase" works without updating the variable with an assignment?

When I try to use this method in this way:

listItems.textContent.toUpperCase();

it doesn't work, but when using it this way:

listItems.textContent = listItems.textContent.toUpperCase();

it works. Why should we do it like this?

2 Answers

Steven Parker
Steven Parker
172,335 Points

The method doesn't change the string it is applied to, it returns a new string with the changes.

You may be assigning the result to the same string, but many times a programmer wants to keep the original string intact, but will use this method and assign the result to a different string.

For flexibility, most methods work this way. It's very rare for a method to change what it is applied to.

It makes sense, thank you.

Tsenko Aleksiev
Tsenko Aleksiev
3,810 Points

In the video, this line of code

listItems.textContent = listItems.textContent.toUpperCase();

is used inside of a function. This part:

listItems.textContent.toUpperCase();

is only telling textContent in the listItems to become all upper case, using the .toUpperCase() method....but you don't save it anywhere. The .toUpperCase() method doesn't change the original string or value, it must be stored in a new value so that it can work properly, this is because string values in javascript are immutable. Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase

I understand now, thank you.