Understanding The 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 tutorial, you learn the basics of JavaScript syntax and how to avoid being scolded by the syntax police!

For Loop in Javascript Console

Saying Precisely What You Mean

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

Tutorial 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:

  • Rotate head toward stairs.
  • Use visual sensors to look for obstacles.
  • If an obstacle is found, determine what it is.
  • 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
  • If there is no obstacle, rotate left foot in the direction of the stairs.
  • Place left foot in front of right foot.
  • Look for an obstacle.
  • Creating magazines
  • Determine whether you’re at the top of the stairs.
  • If you’re not at the top of the stairs, rotate right foot in the direction of the stairs.
  • Place right foot in front of left foot.
  • 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.

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.

Belowing code shows an example of a 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.

the most commonly used storage sizes
Figure 2-1: The output of a JavaScript alert statement.

Notice that the statement in code above 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.

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

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. Belowing code is a JavaScript program that prints out the words “Coding is fun!” 300 times.

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

Follow these steps to test this program:

  • Open the Chrome web browser.
  • 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 above code 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.

The result of running the program for loop.
Figure 2-2: The result of running the program in above code.

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 tutorials 17 and 18.

Take a close look at the above code. 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 above code 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 above code 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.

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!"
Changing string.
Figure 2-3: Changing a string only changes the string.

You would need to write the string as:

"Joe said, \"Hi!\""

Belowing code shows our message printer program with escaped quotation marks in the message.

for (var i = 0; i < 300; i++) { document.write ("Joe said, \"Hi!\""); }

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.

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

Belowing code shows the message printer program with the string in single quotes and double quotes inside the string.

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.

The special meaning of for is explained in tutorial 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

using text in code.
Figure 2-4: Capitalizing a JavaScript keyword wrong produces errors.

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 belowing code.

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

Above the code 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.

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.

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 above code, the first three lines are single‐line comments and the fourth line contains a statement that will be executed, followed by a comment.
  • // The following code won’t run.
    // alert("Watch out!");
    // The next statement will run.
    alert("Have a nice day!"); // pops up a nice message
  • 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, */. Above code shows an example of a multi‐line comment.
  • /*
        AlertMe, by SirNode
        Sir Node makes it easy for people
        to learn application programming
        and website programming