Chapter 3. JavaScript Syntax and Statements

After reading this chapter, you'll be able to

  • Understand the basic rules of using the JavaScript programming language.

  • Place JavaScript correctly within a Web page.

  • Recognize a JavaScript statement.

  • Recognize a reserved word in JavaScript.

A Bit of Housekeeping

The rest of the book looks more closely at specific aspects of JavaScript and how they relate to specific tasks. However, you must walk before you can run, so before examining JavaScript in more depth, you should learn some of its lexical structure—that is, the rules of the language, also known as syntax rules.

Case Sensitivity

JavaScript is case sensitive. The programmer must be aware of this fact when naming variables and using the language keywords. A variable called remote is not the same as a variable named Remote or one named REMOTE. Similarly, the loop control keyword while is perfectly valid, but naming it WHILE or While will result in an error.

Keywords are lowercase, but variables can be any mix of case that you'd like. So long as you are consistent with the case, you can create any combination you want. For example, all these examples are perfectly legal variable names in JavaScript:

buttonOne
txt1
a
C

Tip

You'll typically see JavaScript coded in lowercase except where necessary, like with function calls such as isNaN() which (as you'll learn in Chapter 4,) is a function to determine whether a value is Not a Number (the NaN in the function name).

There'll be much more on variables and their naming conventions in Chapter 4. For now, remember that you must pay attention to the case you use when you write a variable name in JavaScript.

White Space

For the most part, JavaScript ignores white space, or the space between statements in JavaScript. You can use spaces, indenting, or whatever coding standards to which you'd like to adhere that will make the JavaScript more readable. There are some exceptions to this rule. Some keywords, such as return, can be misinterpreted by the JavaScript interpreter if they're included on a line by themselves. You'll see an example of this problem a little later in this chapter.

Making programs more readable is a good enough reason to include white space as necessary. Consider the following code sample. It includes minimal white space and indenting:

function cubeme(incomingNum) {
if (incomingNum == 1) {
return "What are you doing?";
} else {
return Math.pow(incomingNum,3);
}
}
var theNum = 2;
var finalNum = cubeme(theNum);
if (isNaN(finalNum)) {
alert("You should know that 1 to any power is 1.");
} else {
alert("When cubed, " + theNum + " is " + finalNum);
}

Now consider the following code, with indenting. (This code can be found within the code on the companion CD called indentingexample.txt.)

function cubeme(incomingNum) {
    if (incomingNum == 1) {
        return "What are you doing?";
    } else {
        return Math.pow(incomingNum,3);
    }
}

var theNum = 2;
var finalNum = cubeme(theNum);

if (isNaN(finalNum)) {
    alert("You should know that 1 to any power is 1.");
} else {
    alert("When cubed, " + theNum + " is " + finalNum);
}

The second code sample performs just like the first, but it is generally easier to read and follow—at least it appears so to me! I find that it takes a short amount of time to actually write code, but then I spend the next several years working with that code. When I visit the code a year later, I'm much happier if I've made the code more readable and easier to follow.

Comments

Speaking of creating more readable code and maintaining that code over the long term, comments are your friends. Code that seems blatantly obvious now won't be nearly so obvious the next time you look at the code, especially if a lot of time has passed since you wrote it. Comments can be placed into JavaScript code in two ways: multiline and single line.

A multiline comment in JavaScript will look familiar to anyone who has coded in the C programming language. A multiline comment begins and ends with /* and */ respectively, as this code example shows:

/* This is a multiline comment in JavaScript
It is just like a C-style comment insofar as it can
span multiple lines before being closed. */

Single line comments begin with two front slashes (//) and have no end requirement because they only span a single line. An example is shown here:

// Here is a single line comment.

It's perfectly valid to use multiple single-line comments, and I find myself doing so for short comment blocks rather than using the multiline comment style previously shown. For example, look at this block of code:

// Here is another comment block.
// This one uses multiple lines.
// Each line must be preceded with two slashes.

Tip

You may find it quicker to use the two-slash method for small comments that span one line or a few lines. For larger comments, such as those at the beginning of a program or script, the multiline comment style is a better choice because it makes it easier to add or delete information if necessary.

Semicolons

Semicolons are used to delineate expressions in JavaScript. Technically, semicolons are not required for most statements and expressions. However, the subtle problems that you'll encounter if you don't use semicolons can add unnecessary errors and hence unnecessary debugging time. In some instances, the JavaScript interpreter will insert a semicolon when you may not have wanted one at all. For example, consider the statement:

return
(varName);

In all likelihood, you wanted to write:

return(varName);

But JavaScript, acting on its own, inserts a semicolon after the return statement, making the code appear like this to the JavaScript interpreter:

return;
(varName);

This code won't work; the interpreter will misunderstand your intentions. If you were to use this code in a function, it would return undefined to the caller, which is not likely what you want. This is an example where free use of white space is not allowed; you can't successfully use line breaks (explained below) to separate the return keyword from the value that it's supposed to return.

You'll find programming in JavaScript much easier if you use semicolons as a rule rather than trying to remember where you might not have to use them.

But you definitely shouldn't use semicolons in one instance: when using loops and conditionals. Consider this bit of code:

if (a == 4)
{
    // code goes here
}

In this case, you wouldn't use a semicolon at the end of the if statement. The reason is that the statement or block of statements in matching braces that follows a conditional is part of the if statement. A semicolon marks the end of the if statement and, if improperly placed, effectively dissociates the first part of the if statement from the rest of it. For example, this code is wrong (the code within the braces will execute regardless of whether a equals 4):

if (a == 4);
{
    // code goes here
}

Tip

When opening a loop or function, skip the semicolons.

Line Breaks

Related closely to white space and even to semicolons in JavaScript are line breaks, sometimes called carriage returns. Known in the official ECMA-262 standard as "Line Terminators," these characters separate one line of code from the next. Like semicolons, the placement of line breaks matters. As you saw from the example in the previous section, if you try to place a line break in the wrong place, it can result in unforeseen behavior or errors.

Not surprisingly, the most common use of line breaks is to separate individual lines of code for readability. To improve readability of particularly long lines of code, you can also separate some lines of code with line breaks as well. However, when doing so, you should be aware of issues like the one illustrated by the return statement cited earlier, where an extra line break can have unwanted effects on the meaning of the code.

Placing JavaScript Correctly

JavaScript can be placed in a couple of locations within a Hypertext Markup Language (HTML) page: in the <head> </head> section or between the <body> and </body> tags. The most common location for JavaScript has traditionally been between the <head> and </head> tags near the top of the page, though you may encounter some uses for it within the <body> section. In addition, you should declare what type of script you're using. Within the opening <script> tag, declare

<script type = "text/javascript">

Other script types could be declared here, but this is a JavaScript book, so that's the only one I'll be discussing.

One important distinction with JavaScript occurs with pages declared as Extensible Hypertext Markup Language (XHTML). In such pages, the <script> tag must be declared within a CDATA section because otherwise XHTML will try to parse the <script> tag as just another XML tag, and therefore code within the section might not work as you'd expect. Therefore, JavaScript used within strict XHTML should be declared as follows:

<script type="text/javascript">
<![CDATA[

//JavaScript goes here

]]>
</script>

If you place the actual JavaScript code in a separate file (as you've seen), then you don't need to use this ugly CDATA section at all. You'll likely find that for anything but the smallest of scripts, you'll want to define your JavaScript in separate files, usually with the file extension .js, and then link to those scripts within the page. The previous chapter showed this in full detail, but here's a reminder of how you link to a file using the src attribute of the <script> tag:

<script type="text/javascript" src="myscript.js">

JavaScript Statements

Like programs written in other languages, JavaScript programs consist of statements put together that cause the JavaScript interpreter to perform one or more actions. JavaScript statements can be simple or compound, which again is the same as with other programming languages. This section briefly examines the form of JavaScript statements, with the understanding that you've already seen several examples in the previous chapters and that you'll see others throughout the book.

What's in a Statement?

As covered in Chapter 1, a JavaScript statement or expression is a collection of tokens, operators, and identifiers that are put together to create something that makes sense to the JavaScript interpreter. A statement usually ends with a semicolon, except in special cases like loop constructors such as if, while, and for, which are covered in Chapter 5.

Here are some examples of basic statements in JavaScript:

var x = 4;
y = x * 4;
alert("Hello");

The Two Types of JavaScript Statements

JavaScript statements come in two basic forms, simple and compound. I won't spend a lot of time discussing statements simply because you don't really need to know much about them. However, you should know the difference between simple and compound statements. A simple statement is just what you'd expect—it's simple, like so:

x = 4;

A compound statement combines multiple levels of logic. An if/then/else decisional such as the one given here provides a good example of this:

if (something == 1) {
    // some code here
} else {
    // some other code here
}

Reserved Words in JavaScript

Certain words in JavaScript are reserved, which means you can't use them as variables, identifiers, or constant names within your program because doing so will cause the code to have unexpected results, such as errors. For example, you've already seen the reserved word var in previous examples. Using the word var to do anything but declare a variable may cause an error or other weird behavior. Consider this statement:

var var = 4;

The code example won't result in a direct error to a browser, but it also won't work as you meant, possibly causing confusion when a variable's value isn't what you expect.

The following list includes the words that are currently reserved by the ECMA 262 specification.

break

delete

function

return

typeof

case

do

if

switch

var

catch

else

in

this

void

continue

finally

instanceof

throw

while

default

for

new

try

with

Several other words (shown in the following list) are reserved for future use and therefore shouldn't be used within your programs.

abstract

double

implements

private

throws

boolean

enum

import

protected

transient

byte

export

int

public

volatile

char

extends

interface

short

 

class

final

long

static

 

const

float

native

super

 

debugger

goto

package

synchronized

 

A Quick Look at Functions

You've already seen examples of functions in previous chapters. JavaScript has several built-in functions, or functions that are defined by the language itself. I have discussed the alert() function already, but there are several others. Built-in functions depend on the version of the language that you're using. Some functions are available only in later versions of JavaScript, which might not be supported by all browsers. Detecting functions (and objects) is a key method for determining if a visitor's browser is capable of using the JavaScript that you've created for your Web page. This topic is covered in Chapter 14, .

Tip

You can find an excellent resource for compatibility on the Quirksmode Web site (http://www.quirksmode.org/dom/compatibility.html).

Similar to other programming languages, JavaScript also allows user-defined functions. An earlier example in this chapter defined a function called cubeme(), which raised a given number to the power of 3. That code provides a good opportunity to show the use of JavaScript in both the <head> and <body> portions of a Web page.

Placing JavaScript with a user-defined function

  1. Using Microsoft Visual Studio, Eclipse, or another editor, edit the file example1.htm in the Chapter 3 sample files folder.

  2. Within the Web page, add the code shown below in bold type:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <script type = "text/javascript">
    function cubeme(incomingNum) {
        if (incomingNum == 1) {
            return "What are you doing?";
        } else {
            return Math.pow(incomingNum,3);
        }
    }
    </script>
        <title>A Chapter 3 Example</title>
    </head>
    
    <body>
    <script type = "text/javascript">
    var theNum = 2;
    var finalNum = cubeme(theNum);
    
    if (isNaN(finalNum)) {
        alert("You should know that 1 to any power is 1.");
    } else {
        alert("When cubed, " + theNum + " is " + finalNum);
    }
    </script>
    
    </body>
    </html>
  3. Save the page, then run the code or view the Web page in a browser. You'll receive an alert like this:

    image with no caption

The code in this example incorporates the code from the earlier example into a full HTML page, including a DOCTYPE declaration. The code declares a function, cubeme(), within the <head> of the document, like so:

function cubeme(incomingNum) {
    if (incomingNum == 1) {
        return "What are you doing?";
    } else {
        return Math.pow(incomingNum,3);
    }
}

This code accepts an argument called incomingNum within the function. An if/then decisional statement is the heart of the function. If the incoming number equals 1, the function returns the text string, "What are you doing?" If, on the other hand, the incoming number is less than or greater than 1, the Math.pow method is called and passes the incomingNum variable and the integer 3 as arguments. The call to Math.pow in effect raises the incoming number to the power of 3, and this value is then returned to the calling function.

All the previous code was placed within the <head> of the document so it can be called by other code, which is just what we're going to do. The browser then renders the <body> of the document, which includes another bit of JavaScript code. This next bit of code sets a variable, theNum, equal to the integer 2:

var theNum = 2;

The code then calls the previously defined cubeme() function using the theNum variable as an argument. You'll notice that the variable finalNum is set to receive the output from the call to the cubeme() function, as follows:

var finalNum = cubeme(theNum);

The final bit of JavaScript on the page is another if/then decisional set. This code checks to see if the returned value, now contained in the finalNum variable, is a number. To do so, the isNaN() function is used. If the value is not a number, then an alert is displayed reflecting the fact that 1 was used as the argument. (Of course, there could be other reasons why this isn't a number, but bear with me here and play along with my example.) If the return value is indeed a number, then the number is displayed, as you saw from the alert() dialog box shown in step 3 above.

Exercises

  1. Which of the following are valid JavaScript statements? (Choose all that apply.)

    1. if (var == 4) { // Do something }

    2. var testVar = 10;

    3. if (a == b) { // Do something }

    4. testVar = 10;

    5. var case = "Yes";

  2. True or False: Semicolons are required to terminate every JavaScript statement.

  3. Examine this bit of JavaScript. What will be the likely result? (Assume that the JavaScript declaration has already taken place and that this code resides properly within the <head> section of the page.)

    var orderTotal = 0;
    function collectOrder(numOrdered) {
        if (numOrdered > 0) {
            alert("You ordered " + orderTotal);
            orderTotal = numOrdered * 5;
        }
    return orderTotal;
    }
..................Content has been hidden....................

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