Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript and the DOM (Retiring) 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
229,732 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,819 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.