Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops A Closer Look at Loop Conditions

Joseph Michelini
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Joseph Michelini
Python Development Techdegree Graduate 18,692 Points

Is 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?

Joseph Michelini
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Joseph Michelini
Python Development Techdegree Graduate 18,692 Points

Here's the code from the video, btw:

const upper = 10000;
const randomNumber = getRandomNumber(upper);
let guess;
let attempts = 0;
function getRandomNumber(upper) {
  return Math.floor( Math.random() * upper ) + 1;
}
while (guess !== randomNumber) {
  guess = getRandomNumber(upper);
  attempts++;
}
document.write(`<p>The random number was: ${randomNumber}</p>`);
document.write(`<p>It took the computer ${attempts} tries to guess.</p>`);

2 Answers

Steven Parker
Steven Parker
210,850 Points

It 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.