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 A Closer Look at Loop Conditions

Jeremiah Lugtu
Jeremiah Lugtu
9,910 Points

Create a while loop code challenge help concerning shorthand variable declarations

Why does this code work:

var count = 0;

while ( count !== 26) {
  document.write(count + ' ');
    count += 1;
}

but this doesn't:

var count = 0;

while ( count !== 26) {
  document.write(count + ' ');
  var count += 1;
}

Do variable scopes only apply to codeblocks of conditional statements?

Hi Jeremiah,

I'm not 100% sure, but I think since the variable 'count' is a global variable and you are trying to redefine it within the loop, that is causing the error. So, you may be taking away the value of the global variable and only establishing a local variable. I hope that's right and/or helpful. Again, that was a guess and hopefully someone else can better explain that.

-Dan

2 Answers

Per Karlsson
Per Karlsson
12,683 Points

Hi Jeremiah,

You can't declare and increment the variable on the same line. For the same reason that this wouldn't work (try it in the browser console)

var test += 1;

This would work:

var count = 0;

while ( count !== 26) {
  document.write(count + ' ');
  var count;
  count += 1;
}

But it doesn't really make sense to declare the variable count each time you iterate the while loop.

Hope that answers your question.

~Per

Jeremiah Lugtu
Jeremiah Lugtu
9,910 Points

Thank you for your answer, I was trying to have the increments affect the 'count' variable only within the loop's codeblock rather than the global scope of the 'count' variable... Or does that only work with functions (like the example in JavaScript Basics)?

Why is it that we use while(count !== 26);

and not

while( count > 26 );

since it's asking us to write it 26x times and then its suppose to close the loop.

The !== (is not equal value or not equal type)