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

Jonathan Franklin
Jonathan Franklin
3,883 Points

Question about using var

When using a variable that I already made say; var questions = 3; and I go to use it again: var questions -= 1; it won't work. But if I remove var from it like: question -= 1; it works. Does it think I'm trying to create a new variable? Just trying to create "good" habits for writing JavaScript, if one considers that a good habit.

3 Answers

Yes, it does think you are trying to create a new variable. Adding 'var' to the beginning is declaring a new variable. When your referencing the variable to modify etc you don't include the 'var'.

It is thinking exactly that. By saying

var questions = 3;

you're declaring a variable, whereas by ommiting "var" and saying

questions -= 1;

you're assigning it a new value. You need to declare "questions" before doing so though, otherwise you'll end up with a Reference Error.

"var questions -= 1" wont work and will result in a Syntax Error.

andren
andren
28,558 Points

It doesn't think you are creating a new variable, you are creating a new variable. The var keyword is used to declare variables, declare in this context being a fancy word for create. When you are just referencing an existing variable either to get or change its value you are not meant to include the var keyword.

Edit: Oops seems I was a bit late to the party :smile: