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

General Code Question

I created the following code during a workshop.

Question: Why does the line "document.write(text + ' var-text ' + "<br>");" give me an answer of, for example: 7, 6, 11, 7, var-text and not just 7, ? Why, as the code repeats itself, does it write all of the previous values of 'text'. I would have thought that the value of 'text' would either reset itself or constantly increase in value. What am I missing here?

Thanks very much in advance.

CODE text = ''; a = 3; b = 2; i = Math.floor(Math.random() * 10); while ( i !== 8 ) { text += (i + a + b) + ', '; document.write(i + 'var-i1 ' + "<br>"); i = Math.floor(Math.random() * 10); document.write(text + ' var-text ' + "<br>"); document.write(i + ' var-i2 ' + "<br>"); }

EXAMPLE RESULTS 2 var-i1 7, var-text 1 var-i2 1 var-i1 7, 6, var-text 6 var-i2 6 var-i1 7, 6, 11, var-text 2 var-i2 2 var-i1 7, 6, 11, 7, var-text 8 var-i2

2 Answers

In your loop you're extending your text variable, beucase you're using +=. If you want to reassign the text variable with a new value, you should only be using an =.

Hi Stephan, I took your advice and I played around w/the code.
When I set (text = text + i + a + b + ', ';) I get a result of: text(1), text(2), text(3), etc...,
When I set (text = i + a + b + ', ';) I get one result of: text. I think I got it.

Thank you