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

Derek Miller
Derek Miller
6,466 Points

How do you know which variables to place at the top of the document?

I have a little bit of experience in science research, so up to this point I've been seeing variables like they are in a lab experiment, and have been creating a variable at the top for all the things that impact the "system"/code. Is this a good way of thinking about it? It hasn't hurt me thus far, but sometimes I create variables that I don't end up using or defining. Does anybody else experience this?

3 Answers

Steven Parker
Steven Parker
229,981 Points

JavaScript doesn't care if you create variables and don't use them, but it would be good practice to remove them once your program is complete.

Declaring variables at the start of the program (or code block) is also a "best practice", and often necessary if you declare them with "let". If you use "var" the system will "hoist" them for you, but this should not be relied on.

Alexander Rodriguez, MD
Alexander Rodriguez, MD
6,642 Points

It's a good idea to define your variables and constants in a single place so you can easily find them later as you refactor your code. If you spread them all over the place it becomes more difficult to find them as your code evolves. In practice, as you're experience grows, you'll develop your own consistent and personal style that bests works for you. As your programming knowledge increases, you'll learn new ways to organize your code. For example, when doing object oriented programming, your variables will be organized by their respective class definitions. When writing javascript, I tend to keep them at the top of the page. I hope this helps.

Derek Miller
Derek Miller
6,466 Points

I guess a clearer way of asking this is that I noticed the teacher seems to always know what variables to list at the beginning before he digs into the rest of the code. Does this realistically happen, or is your grouping of variables usually something you add to gradually as you find you need one later on? Does this make sense?

Steven Parker
Steven Parker
229,981 Points

It happens both ways. If you have a clear idea of how the program will work, you can start by listing the variables you need. But you discover while writing the code that you need one or more additional ones, you would then return to the top of the program and add them.