Chapter 2

Understanding Syntax

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!

image

Saying Precisely What You Mean

In order to be compiled correctly into machine language instructions, programs need to be written very precisely.

remember Chapter 1 explains what a program is and how programs are translated into machine language using the process called compilation.

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:

  1. Rotate head toward stairs.
  2. Use visual sensors to look for obstacles.
  3. If an obstacle is found, determine what it is.
  4. If the obstacle is a cat, try to lure the cat away from the top of the stairs by:
    • Throwing a toy down the hall
    • Speaking the cat’s name
    • Gently nudging the cat with your hand until it walks away
  5. If there is no obstacle, rotate left foot in the direction of the stairs.
  6. Place left foot in front of right foot.
  7. Look for an obstacle.
  8. Determine whether you’re at the top of the stairs.
  9. If you’re not at the top of the stairs, rotate right foot in the direction of the stairs.
  10. Place right foot in front of left foot.
  11. Repeat steps 1 through 10 until you’re at the top of the stairs.

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.

technicalstuff You can find out more about how to control robots with JavaScript by visiting http://nodebots.io!

Making a Statement

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.

image

Figure 2-1: The output of a JavaScript alert statement.

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.

tip The semicolon is what separates one statement from another, just as a period separates one sentence from another. Every statement should end with a semicolon.

Following the Rules

tip JavaScript has several rules that must be obeyed if you want your computer to understand you. The first two rules are:

  • Spelling counts.
  • Spacing doesn’t count.

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:

  1. Open the Chrome web browser.
  2. Open the JavaScript Console from the More Tools menu under the Chrome menu.

    tip You can also use the keyboard combination to open the JavaScript Console. Press maccmd+Option+J (Mac) or Ctrl+Shift+J (Windows).

  3. 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.

image

Figure 2-2: The result of running the program in Listing 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.

Using text in strings

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!”

image

Figure 2-3: Changing a string only changes the string.

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.

tip The way to put quotation marks inside a string is by using a backslash () before the quotation marks. Using the backslash in a string tells JavaScript that the next character is something special and doesn’t mean what it normally would mean. When you add a backslash before a quotation mark in a string, it’s called escaping the quotation mark.

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!""); }

technicalstuff You might be asking yourself now, “If the backslash is used to tell JavaScript that the next character is special, how do I print out a backslash?” Great question! The answer is just to use two backslashes (\) for each backslash that you need to print out.

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!" '); }

Using text in code

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.

image

Figure 2-4: Capitalizing a JavaScript keyword wrong produces errors.

remember The special meaning of for is explained in Chapter 17.

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!

Paying attention to white space

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.

tip 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.

tip We recommend using 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!

Making comments

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:

  • To tell their future selves, and anyone else who works on the program in the future, why they wrote something in the particular way they did
  • To describe how the code they wrote works
  • To leave themselves a note telling what they still need to do, or to list improvements that they intend to make at a later date
  • To prevent JavaScript statements from running

JavaScript has two different kinds of comments: single-line and multi-line.

  • Single-line comments: Single-line comments cause everything following them on the same line to be a comment. To create a single-line comment, use two slashes (//) back to back. For example, in Listing 2-6, the first three lines are single-line comments and the fourth line contains a statement that will be executed, followed by a comment.
  • Multi-line comments: Multi-line comments are comments that can be more than one line long. To create a multi-line comment, start with /* and end the comment with the exact reverse, */. Listing 2-7 shows an example of a multi-line comment.

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.

*/

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.119.148