JavaScript For Kids For Dummies
Book image
Explore Book Buy On Amazon

White space is all the spaces, tabs, and line breaks in your program. JavaScript ignores white space between words and between words and symbols in code. For example, in a message printer program, you could make the whole thing easier for people to read by spacing it out over multiple lines, as shown here.

for (var i = 0; i < 300; i++) {
  document.write ("Coding is fun!");

Notice that line breaks are inserted after the opening curly bracket ({) and before the ending curly bracket (}). Curly brackets are used for grouping pieces of code (also called statements) together into what's called a block. In this program, they mark the part of the program that should be repeated 300 times — namely, printing out a message.

Curly brackets are a good spot to put some white space to help you read the code more easily. Another great spot to put a line break is after each semicolon (;). In JavaScript, the semicolon is used to mark the end of a statement, much as a period is used to mark the end of a sentence in English.

If you try to run the program split over three lines in the JavaScript Console in Chrome, you'll get an error message when you press Return (Mac) or Enter (Windows) after the first line. This is because the console tries to run your code every time you press Return or Enter, and the first line (ending with {) isn't a complete JavaScript statement. To enter this code into the console with line breaks, hold down the Shift key while pressing Return or Enter after each of the first two lines.

Notice that the statement between the curly brackets is indented. The indentation helps people reading the code to see that this statement is happening inside another statement — namely, the for statement that creates the loop.

Use either two spaces or four spaces to indent statements. Some people use tabs to indent statements. Which one you use is up to you. Once you decide, however, stick with it. If you use two spaces to indent code inside of a block, you shouldn't sometimes use four spaces or a tab. Neatness counts!

About This Article

This article is from the book:

About the book authors:

Chris Minnick and Eva Holland are experienced web developers, tech trainers, and coauthors of Coding with JavaScript For Dummies. Together they founded WatzThis?, a company focused on training and course development.

This article can be found in the category: