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 trialjohn larson
16,594 PointsI'm almost afraid to ask...
The +1 in line 3 of the code for "single generator" goes outside the parenthesis
The + 1 in line 6 of the double generator goes inside the parenthesis
why is it different though the concept for the codes seems to be the same
<li>code for the single generator</li>
<pre>
var userInput = prompt('pick a number from 1 to ~');
var userNumber = parseInt(userInput);
var randomNumber = Math.floor(Math.random() * userNumber) + 1;
alert( randomNumber + ' is a number between 1 and ' + userNumber);
</pre>
<li>code for double generator</li>
<pre>
var userInput1 = prompt('pick a low number');
var lowNumber = parseInt(userInput1);
var userInput2 = prompt('pick a high number');
var highNumber = parseInt(userInput2);
var randomNumber = Math.floor(Math.random() * (highNumber -
lowNumber + 1 ) + lowNumber);
alert(randomNumber + ' is a number between 1 and ' + highNumber );
</pre>
1 Answer
Andrew VanVlack
20,155 PointsWhen the javascript reads that line, it will start running the code starting at the inner most set of parenthesis. Identical to math, the multiplication gets ran next and then the addition. Really it dose not matter with the first equation as it will run in the same order if its inside or outside. On the second algorithm we need the math to work in a specific order so they use the parenthesis.
This is all set in operator precedence. Check out this MDN on operator precedence
Samuel Webb
25,370 PointsSamuel Webb
25,370 PointsCode fixed to be more readable.