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

Pros and cons of not creating another variable called Shout?

I tried this "app" prior to the instructor actually going through how to create it. My solution did not use the extra variable called "shout" in or order to hold the uppercase information.

My solution:

var stringToShout = prompt('What should I shout'); stringToShout = stringToShout.toUpperCase(); stringToShout += "!"; alert(stringToShout);

Instructors Solution:

var stringToShout = prompt('What should I shout'); var shout = stringToShout.toUpperCase(); shout += "!!!"; alert(shout);

Can someone give me the pros and cons of my solution vs the instructors?

1 Answer

Mike Wagner
Mike Wagner
23,888 Points

I'm not sure if it's a mistype when you were posting the question or not, but the way the instructor code is writen should alert(shout); not alert(stringToShout);, just throwing that out there because it made me chuckle a bit. Anyway, going back to your question.. there's a slight performance difference between reassigning (what you do) and creating (what the instructor..supposedly?..does). I wont get into all the technicalities, as for something like this, it's almost negligible. It is worth noting, however, that usually the difference between reassignment and creation boils down to how often a variable is used in a program and what kinds of things you're doing with it. If it's being accessed on a regular basis (i.e. every page load, anytime something on the page updates, anytime data is sent or processed, etc.) then it's better to cache it as a variable and call it good. In a case like this, you're probably good with throwing it away by using your method and just overwriting the variable via reassignment every time, but if you were to do a bunch of stuff with shout (the processed string) or you needed to retain the original stringToShout it's better to store it as a new variable.

Thanks for the replay mike. I can see now where one could run into trouble in a larger program.