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 trialJoseph Michelini
Python Development Techdegree Graduate 18,692 PointsIs this code not problematic, due to the variable sharing a name with the parameter?
Wouldn't it be better to name the first variable anything but "upper," the exact name of the parameter that the function accepts? Couldn't you either eliminate that variable and type the following:
const randomNumber = getRandomNumber(10000);
let guess;
let attempts = 0;
function getRandomNumber(upper) {
return Math.floor( Math.random() * upper ) + 1;
}
while (guess !== randomNumber) {
guess = getRandomNumber(10000);
attempts++;
}
document.write(`<p>The random number was: ${randomNumber}</p>`);
document.write(`<p>It took the computer ${attempts} tries to guess.</p>`);
or name the variable something else?
2 Answers
Steven Parker
231,275 PointsIt poses no technical problem because inside the function, the name refers only to the parameter. The global variable is said to be "shadowed" (made not available) by the parameter.
However, it could be a bit confusing to someone reading the code, so having unique variable names is a good practice even if not technically necessary. That way, you could still keep the code "DRY" by retaining the constant so the literal value did not need to be repeated.
Joseph Michelini
Python Development Techdegree Graduate 18,692 PointsThank you Steven!
Joseph Michelini
Python Development Techdegree Graduate 18,692 PointsJoseph Michelini
Python Development Techdegree Graduate 18,692 PointsHere's the code from the video, btw: