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 `do ... while` Loops

why isnt there a execution for the while loop?

why is it like this do { // execute code } while (condition);

but not like this do { // execute code } while (condition) { //execute code };

so far i think that do will execute the code once in any case and if the while condition is not true it will keep asking the do again and again until while is = false or conditions are not met.

so what would happen if we dont use return num i mean the value of the function is already stored in num or it isnt? var num = Math.floor(Math.random() * upper) + 1;

Steven Parker
Steven Parker
231,236 Points

Without "return num", then "randomNumber" would get "undefined" instead of the number.

im sorry but i still dont get it...

Steven Parker
Steven Parker
231,236 Points

Perhaps some time spent experimenting would be more valuable than further explanations.

its not like im not trying im just understanding the concept of return. i searched a lot too

1 Answer

Steven Parker
Steven Parker
231,236 Points

A loop has only one code block that repeats. In a standard "while" loop, the block comes after the "while". But in a "do...while" loop, the block comes between the "do" and the "while".

You are correct that in a "do...while" loop, the block will always be executed at least one time.

thank you

one more thing why is there a return num in the function? var randomNumber = getRandomNumber(10); var guess; var guessCount = 0;

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

Steven Parker
Steven Parker
231,236 Points

The "return num" gives the random number just created back to the part of the program that called the function.

so basically return num stops the function from running again and stores the value of random num generated when the getrandomnumber function first ran and as the function has a return value it wont run again because the value is stored in num? or im entirely wrong.

Steven Parker
Steven Parker
231,236 Points

The "getRandomNumber" function has no loop, so it won't "run again" unless it is called again.

The "return" is only used to pass back the value in "num". The code that called it stores it in "randomNumber".