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

Garbage values in JavaScript?

/* Is there such a thing as garbage values in JavaScript?

Am reading that in C, if you define a variable without initializing it to a specific value, that variable may in fact have a garbage value stored inside it. I noticed that in the apps.js program, the instructor indicated that the condition in the while loop is checked before executing. Does that imply that there is no essence of garbage value in JS? */


var upper = 10000;
var randomNumber = getRandomNumber(upper);
var guess;
var 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 + " attempts to get it right.</p>");

2 Answers

In JavaScript, a variable that has not been assigned a value is of type undefined. You can check this by calling console.log(guess) before the guess variable is assigned a value.

In C, "garbage value" refers to the fact that an unassigned variable refers back to its location in memory, which is usually represented as a hexadecimal number. When you learn about pointers in C, you will learn all about this. To answer your question, no, variables do not behave this way in JavaScript.

Awesome response. Thanks!