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

Bram Huisman
Bram Huisman
7,387 Points

While loop runs 1 time

Hi there,

I am making a simple higher or lower card game. I think i've the correct code but my while loop only runs one time.

Here is a JSbin of my code: http://jsbin.com/tenuzemequ/edit?js,console

This is what i am trying to achieve:

  • Draw a card
  • Log the card that has been drawn
  • Ask the player if the next card will be "higher" or "lower"
  • If the answer is correct ask if the next card will be "higher" or "lower"
  • and so fort
  • if the answer is incorrect break the while loop en start over again by refreshing.

Does someone know what i am doing wrong?

2 Answers

Steven Parker
Steven Parker
229,788 Points

:point_right: It looks like JSBin may have a bug. :beetle:

I tried your program elsewhere and it seems to work as intended. You may want to try moving your project to another venue, such as a Treehouse workspace, or a different 3rd party REPL.

I also have a few suggestions for improvement in your program (none that affect the JSBin issue):

  • rework the program so all output is done using prompt or alert instead of console.log
  • you could also do all interaction through the DOM, and "higher" and "lower" could be buttons
  • prevent picking the same card twice in a row (unless you want an occasional no-win scenario)
  • move the rest of the code into the function, since most of the game is already there
  • test booleans directly instead of using a comparison

For an example of the last suggestion:

  while (correctAnswerGiven === true)  // instead of this...
  while (correctAnswerGiven)           // ...just do this
Bram Huisman
Bram Huisman
7,387 Points

Thx for checking!

And yes i know it needs some improvement! Really thanks for your suggestions! :)

Greetz,

Jonathan Grieve
MOD
Jonathan Grieve
Treehouse Moderator 91,252 Points

I think it's because you're changing the boolean value of correctAnswerGiven to false which of course you want to do, but not providing a means for the loop to reset the value to try again. If you don't do that, the value will never again be true and the loop won't start again.

Try assigning the value to true at the top of the loop.

Bram Huisman
Bram Huisman
7,387 Points

Thanks for the heads up!