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 Tracking Multiple Items with Arrays Build a Quiz Challenge, Part 1 Solution

Why are some variables undefined?

My question is, how do we decide to use "var correctanswer = 0;" while other variable is "var question;"

Why did we asign correct answer variable to zero. If I use "var correctanswer;" it is not working. What is the difference between these two way of code, and if there is a course in treehouse about this subject, would you please share the link? Maybe I missed that class.

3 Answers

I Dilate
I Dilate
3,983 Points

Asli, what's the specific context of your question?

"var correctanswer;" creates a variable but uses value "undefined" for it, i.e. you can assign it a value later on in your code.

"var correctanswer = 0;" creates a variable and defines it as an integer with the value of zero. This is useful in cases where you need to define an integer of zero at the start of your code, then apply some arithmetic to it. For example, if you want to add 1 to it using a loop every time your user gets a correct answer.

Note, you won't be able to do arithmetic like add 1 to an "undefined" variable, because it's not set to an integer or float yet.

Thanks a lot Dilate!

I Dilate
I Dilate
3,983 Points

No problem asli. Good luck with the rest of the lessons!