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 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
229,785 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.