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 trialSereta Baldwin
6,183 PointsIs there a reason to have the extra variable?
I was just wondering if there was a reason (best practice or something?) as to why the second variable was there. I learnt a bit of Python previously and the teacher on that course always went on about efficient code and how you want to get to the end result with the least amount of code possible. Does that hold true with JavaScript/ all programming languages? Cause I would've thought that the following would've been more efficient, but maybe there are other considerations in JS that I'm not aware of yet:
const stringToShout = prompt(`What do you want to shout?`);
const shoutMessage = `<h2>The message to shout is: ${stringToShout.toUpperCase()}</h2>`;
Thanks to anyone who takes the time to respond! :)
1 Answer
Zimri Leijen
11,835 PointsYou could do that, but fewer lines is not always better.
It's good practice to be very explicit with your codes, everything should do exactly what the function says it does, with ideally no side effects.
Clear variable names and function names will help, as well as each function having only a single task.
If you want to be very strict about this, then changing the case to uppercase can be seen as a task, while printing the message is another, unrelated task.
While in this particular example it's splitting hairs, in a real program it will quickly become messy if you combine multiple functionalities within a single function. Especially when later on you call a function from a different context, but forgot about the side effect, and then your function gives you unexpected results.\
In this case, shoutMessage seems clear enough in intention, so it's an edge case.
Sereta Baldwin
6,183 PointsSereta Baldwin
6,183 PointsThat was a fabulous answer to my question! I realise in this case it probably doesn't make much difference, but it's really nice to understand these things from the get-go so I can form good habits that might help me down the line (as you mentioned). Thanks so much for taking the time! :)