Chapter 2
Just as spoken languages have rules (called grammar), computer programming languages have rules (called syntax). When you understand the basic rules of speaking JavaScript, it actually looks similar to English.
If you thought that your teacher correcting you when you say “ain’t” was strict, wait until you see how strict JavaScript is! It won’t even listen to a thing you say if you make certain kinds of syntax errors.
In this chapter, you learn the basics of JavaScript syntax and how to avoid being scolded by the syntax police!
In order to be compiled correctly into machine language instructions, programs need to be written very precisely.
As a programmer, your job is to think about the big picture of what you want the program to do, and then break it down into bite-size steps that can be accomplished by the computer without errors. For example, if you wanted to ask a robot to go downstairs and get you a sandwich, you might start your instructions like this:
You’ve written 11 instructions already and the robot hasn’t even started walking down the stairs, much less making a sandwich!
A real computer program to tell a robot to go downstairs and make a sandwich would need to contain far more detailed instructions than the ones shown here. At each step along the way, each motor would need to be told precisely how long to turn on, and each possible condition and obstacle would need to be described and dealt with in detail.
All these instructions need to be written as individual JavaScript commands, or statements.
In English, we talk in sentences. In JavaScript, a single instruction to the computer is called a statement. Like a sentence, statements are made up of different parts and have certain rules that they must follow in order to be understood.
Listing 2-1 shows an example of a statement.
Listing 2-1 A JavaScript Statement
alert("Coding is fun!");
This statement causes a web browser to open up a popup alert window with the sentence “Coding is fun!” If you type this statement into the JavaScript Console in Chrome, you’ll see something like what’s shown in Figure 2-1.
Notice that the statement in Listing 2-1 contains a keyword, some symbols (parentheses and quotes), and some text (Coding is fun!), and it ends with a semicolon.
Just as an infinite number of sentences can be written using English, an infinite number of statements can be written with JavaScript.
The word alert is an example of a JavaScript keyword. Many JavaScript statements begin with keywords, but not all of them do.
Let’s take a look at each of these rules in more detail. We’ll write a new message printer program to serve as an example. Listing 2-2 is a JavaScript program that prints out the words “Coding is fun!” 300 times.
Listing 2-2 A Program to Print a Message 300 Times
for (var i = 0; i < 300; i++) { document.write ("Coding is fun!"); }
Follow these steps to test this program:
Open the JavaScript Console from the More Tools menu under the Chrome menu.
You can also use the keyboard combination to open the JavaScript Console. Press +Option+J (Mac) or Ctrl+Shift+J (Windows).
Type the program in Listing 2-2 onto one line in the JavaScript Console and press Return (Mac) or Enter (Windows).
If you entered everything correctly, you’ll see the message appear in your browser window 300 times, as shown in Figure 2-2.
This “Coding is fun!” program uses a technique called a for loop in order to do something many times with only a little bit of code. We talk more about for loops in Chapters 17 and 18.
Take a close look at the code in Listing 2-2. Notice that the text that gets written to the browser window is enclosed in quotes. The quotes indicate that this text is to be treated as words, rather than as JavaScript code.
In programming, we call a piece of text inside of quotes a string. You can remember this name by thinking of text inside quotes like a piece of string with letters, numbers, and symbols tied to it. These letters stay in the same order and each one takes up a certain amount of space on the string.
For example, try typing the code from Listing 2-2 into your JavaScript console again, but change Coding is fun! to another message, such as what you want for lunch or dinner.
Figure 2-3 shows the output of the program from Listing 2-2 when the message is changed to “I want pizza for lunch!”
Any character you can type can be put into a string. However, there’s one important exception that you need to remember: If you want to use quotation marks inside a string, you have to tell JavaScript that the quotation marks are part of the string, rather than the end of the string.
For example, if you want to change the string to:
Joe said, "Hi!"
You would need to write the string as:
"Joe said, "Hi!""
Listing 2-3 shows our message printer program with escaped quotation marks in the message.
Listing 2-3 Escaping Quotation Marks
for (var i = 0; i < 300; i++) { document.write ("Joe said, "Hi!""); }
As with most things in JavaScript, there is another way to use quotes inside a string: by surrounding the string with different quotes. JavaScript doesn’t care whether you use single quotes (') or double quotes (") to mark text as a string, as long as you use the same type of quotes at the beginning and end of the string.
If you surround your string with single quotes, you can use all the double quotes that you want inside the string, without escaping them. But single quotes must be escaped.
If you surround your string with double quotes, you can use all the single quotes you want inside the string, but double quotes must be escaped.
Listing 2-4 shows the message printer program with the string in single quotes and double quotes inside the string.
Listing 2-4 Double Quotes within Single Quotes
for (var i = 0; i < 300; i++) { document.write (' Joe said, "Hi!" '); }
Unlike in strings, the contents and spelling of text outside of quotes matters a lot. When text isn’t surrounded by quotes (single or double) in JavaScript, it’s considered part of the code of the JavaScript program.
JavaScript code is very picky about spelling and capitalization. In JavaScript code, the following words are completely different:
FOR
for
For
Only the one in the middle means anything special to JavaScript. If you try to use the other two in the message printer program, you’ll get an error, as shown in Figure 2-4.
JavaScript is also very picky about spelling. Many times, when we’re coding and something just isn’t working right, the problem turns out to be that we accidentally left out a letter or mixed up the order of two letters.
Just as typos in writing often go unnoticed, these types of errors can be very difficult to track down, so get into the habit early on of typing slowly and carefully and you’ll save yourself a lot of time in the long run!
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 our message printer program, we could make the whole thing easier for people to read by spacing it out over multiple lines, as shown in Listing 2-5.
Listing 2-5 White Space Makes Programs Easier to Read
for (var i = 0; i < 300; i++) {
document.write ("Coding is fun!");
}
Listing 2-5 shows the way that we would recommend spacing out this program.
Notice that we’ve inserted line breaks 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.
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.
JavaScript comments are a way that you can put text into a program that isn’t a string or a statement. This may not sound so great, but the thing that makes comments so important and useful is precisely that they don’t cause JavaScript to do anything at all.
Programmers use comments within their code for several reasons:
JavaScript has two different kinds of comments: single-line and multi-line.
Listing 2-6 Single-Line Comments
// The following code won't run.
// alert("Watch out!");
// The next statement will run.
alert("Have a nice day!"); // pops up a nice message
Listing 2-7 A Multi-Line Comment
/*
AlertMe, by Chris Minnick and Eva Holland
A program to alert users that they are
using a JavaScript program called AlertMe,
which was written by Chris Minnick and Eva
Holland.
*/
18.222.119.148