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

I'm confused why my 'if' statement doesn't work.

Ok, so everything in this function works fine, but I want the loop to stop after 5 times... What am I doing wrong??

var response;



function myOldestPossession(name) {
  for ( var i = 0; i <= 5; i +=1 ) {
    do {
response = prompt('What is the oldest possession you still have had?');
}
  while (response !== name)
    alert('That\'s kinda weird dude!');
    break;
     if (response !== name && i >= 5) {
    alert('You have a terrible memory and you smell bad');
    }
  }

  }

myOldestPossession('Vodka Bottle');

1 Answer

Steven Parker
Steven Parker
243,318 Points

There's a few odd things here:

  • the "for" loop has a limit of 5, but the "do...while" loop inside it runs forever until it gets a match
  • the "for" loop has a "break" that will end it during the first pass
  • the "if" statement will never execute because of the "break"

how would I rearrange my code in order for my "if" statement to be what I'd hoped it would be??

Steven Parker
Steven Parker
243,318 Points

I'm not sure I entirely understand your intentions by reading the code, but some things you might change:

  • remove the "do" and "while" lines (leave the "prompt")
  • move the "break" statement into the "if" block (after the "alert")

If that's not it, perhaps it will get you close enough that you can take it from there.