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

why can't i just write "while (guess !== randomNumber)" instead of creating a boolean ? worked for me

var randomNumber = getRandomNumber(10); var guess; var guessCount = 0;

function getRandomNumber( upper ) { var num = Math.floor(Math.random() * upper) + 1; return num; }

do { guess = prompt("enter a number between 1 and 10"); guessCount+=1;

if (parseInt(guess) === randomNumber) { break; } } while ( guess !== randomNumber)

document.write("The random number was " + randomNumber + " it took you " + guessCount + " trys");

1 Answer

Steven Parker
Steven Parker
243,656 Points

It works, but because of the "if" statement with the "break" in it — the "while" condition isn't doing anything. But you had a good idea, and if you just add type conversion (or use the converting comparison operator) you can eliminate the "if" statment (and "break") entirely:

} while (parseInt(guess) !== randomNumber);

But the purpose of the lecture is to show how boolean variables can be used, and the original code gives a clear example. As a "best practice" developer, you'll employ your skills to create code that's both clear and efficient, but in the courses you can expect the teachers to occasionally forgo efficiency when illustrating a particular principle.