Good Habits![[next]](../../img/ltp/arrow-next.gif)
Before moving on, let's discuss a few good habits. These recommendations will help you write code that is easy to read and understand, both by you and other people down the line. The easier it is to understand what's going on in a program, the less likely it is that the program contains a bug. So a simple way to write fewer bugs is to write code that is easy to understand.
var to declare your variablesAs we discussed in the chapter on variables, it's good practice to use var the first time you create a variable. Programmers like to see where you declare your variables for the first time, so they can get a sense for the "scope" of your variable. Do you only use it inside a particular function? Or is it "global" (can it be used in all functions)? var makes it clear. (In addition, JavaScript will take notice, and will in some cases point out when you access a variable incorrectly.)
In many languages, the semicolon character (;) must be used to end each statement. In JavaScript, this is optional, and to keep things simple we have so far been omitting them in our examples. However, as you write longer programs, using semicolons is an important way to clearly demark where statements begin and end.
So where exactly do you put the semicolons? After each "statement". A statement can be an assignment (x=y;), a function call (printp("Hello, Dolly!");), a return (return 12;), or anything else that could normally be put on just one line. We'll start using semicolons in the examples of the next chapters, so you can get a sense for where they belong. (Another side benefit of using semicolons is that you can put multiple statements on one line, like print("Hi"); print("there");.)
Writing comments in your code is an essential habit to have, especially when your code isn't obvious. Comments are useful to other people reading your code, including (and perhaps, especially) your future self!
To make a comment, just put two slashes (//) in your code, and then put whatever text you want on the rest of the line. Comments don't cause anything to happen; they're just a way to add notes to your code.
To make a comment span multiple lines, put /* before your comment and */ after it. For example:
|
1
2 3 4 5 6 7 // Prints hello printp("Hello, World!"); // Hello, world! /* This is a longer comment. On multiple lines. Kthxbye. */ printp("Goodbye!"); |
Click to run the code. |
To get a sense for how much commenting is appropriate, keep an eye out for the content and quantity of comments in the examples in the next few chapters.
Remember these habits and you'll save yourself a lot of headaches in the future!