Team LiB
Previous Section Next Section

Lexical Definition

The lexical definition of a language is simply the words that are used to write statements in that language. In the case of JavaScript, the lexical definition is borrowed in large part from languages such as C, C++, and Java. These languages, and JavaScript, have three basic types of statements or "words," that make up the language: assignment statements, selection statements, and iterative statements.

Assignment statements make up a majority of the program source. This type of statement includes variable declaration, class definition, and user-defined functions. Selection statements provide a way to choose between two or more execution paths in a program. Iterative statements provide a way for a block of code to be executed zero or more times consecutively. Assignment statements are covered later in this chapter, and selection and repetition statements are covered in Chapter 2, "Selection and Repetition Statements."

In addition to specifying the words that make up the language, the lexical definition of a language also specifies how a programmer can name variables and to what format literal definitions must conform. In JavaScript, the identifiers used to name variables must follow several rules; I'll explain these rules in the following section. Literals in JavaScript consist of strings and numbers. Strings are always enclosed in quotation marks (either single ' or double '') and numbers are not.

JavaScript Identifiers

Most of the JavaScript statements you write will request data from the client Web browser or from the server from which the Web page originated. In order for that data to be useful, you need a place to store it. To facilitate the storage of data, JavaScript gives you the ability to declare variables to store and to symbolically use the data. Each variable that is declared will have a name, or identifier, that allows the data to be referred to easily. Examples of identifiers that might be used in JavaScript are: counter, userName, and listItem97.

When creating an identifier, you should remember the following very important guidelines:

  • The first character of an identifier must be an ASCII letter, an underscore (_), or a dollar sign ($).

  • An identifier must never begin with a number.

  • An identifier must never consist entirely of JavaScript reserved words. A complete list of JavaScript's reserved words can be found later in this chapter.

  • JavaScript is a case-sensitive language, and so, for example, casetest, CaseTest, and caseTest can all be used simultaneously because they are considered different identifiers by the interpreter.

Identifiers are used not only to name variables, but also to identify user-defined functions and classes. Careful selection of identifier names will help promote readability and help with future code maintenance. See Table 1.1 for a short list of identifiers and their descriptions.

Table 1.1: Bad and Good Identifiers

Bad Identifier

Reason

Good Identifier


7th_element

Begins with number.

element_7

@address

Does not begin with _, $, or letter.

address

in

Is a JavaScript reserved word.

Input

Following is a simple example that demonstrates declaring variables and JavaScript case-sensitivity:

<html>

  <head> 
    <title> 
      JavaScript Professional Projects - Identifiers and literals
    </title> 

    <script language="JavaScript">
    <!-- 
      var casetest = "Once apon a time";
      var CaseTest = 42;
      var caseTest = new Date();<BR>
    // --> 
    </script>
  </head> 

  <body> 

    <center> 
      <font size=6>JavaScript Professional Projects</font><br>
      <font size=4>Chapter 1: Identifiers and literals</font>
    </center> 

    <br><br> 

    <p>
    The value of <font face="Courier New">casetest</font> is: <b>"
    <script language="JavaScript">
    <!-- 
      document.write( casetest );
    // --> 
    </script>
    "</b>. It was initialized to that string literal when
    it was declared.

    <br><br> 

    The value of <font face="Courier New">CaseTest</font> is: <b>
    <script language="JavaScript">
    <!--
      document.write( CaseTest );
    // --> 
    </script>
    </b>. It was initialized to that number literal when
    it was declared.

    <br><br> 

    The value of <font face="Courier New">caseTest</font> is: <b>
    <script language="JavaScript">
    <!-- 
      document.write( caseTest ); 
    // --> 
    </script>
    </b>. It was not initialized with a literal at all.
    Instead it was declared as a date object.
   </p>

  </body>

</html>

In this example, three variables—casetest, CaseTest, and caseTest (notice the different capitalization)—are declared, and each is assigned a different value. casetest was assigned a string value, CaseTest was assigned an integer value, and caseTest was declared as a Date object. In the body of the page, each variable is used in order to show the lack of ambiguity of JavaScript's case-sensitive design.

JavaScript Literals

A literal is data that has been entered directly into the source code of a program. Some examples of literals are 42, 3.14, and "Once upon a time". Literals are commonly used to initialize the value of a variable. For example, if a loop uses a counter, it might be declared as follows: var counter = 0; The name counter is an identifier and the name of the variable, while 0 is a literal and the initial value of counter. Literals can be used to initialize variables to a number, boolean, or string value.

Reserved Key Words

JavaScript, like almost all programming languages, has a list of reserved words that are used directly by the language itself and, consequently, cannot be used as variable names. Key words, or lexemes, make up the lexical definition of a language. A complete list of JavaScript's reserved words is as follows:

abstract

boolean

break

byte

case

catch

char

class

const

continue

debugger

default

delete

do

double

else

enum

export

extends

false

final

finally

float

for

function

goto

if

implements

import

in

instanceof

int

interface

long

native

new

null

package

private

protected

public

return

short

static

switch

synchronized

this

throw

throws

transient

true

try

typeof

var

void

while

with

   

The list of reserved words makes up the vocabulary of the JavaScript language. By combining these words in various ways, the full power of the language is realized.

Although it is possible to use the reserved words as identifiers if you give them different capitalization, it is strongly discouraged because it hampers readability, as you can see in the following example:

var Var = 9 >= 7;
var True = false;
var If = Var && True;
if( If )
{
  document.write( "This is very confusing." );
}

Clearly, using key words in any form can lead to unreadable code.

Comments

Comments are a very helpful feature of every programming language. Adding comments allows a future reader of your source code to understand what you were thinking when you wrote the code.

There are two types of comments in JavaScript, block comments and line comments. Block comments are started by a /* symbol and terminated by a */. All text in between these two symbols will be ignored by the browser's interpreter. Block comments are useful when you need to leave a longer comment, such as a program header or description of user-defined functions. Line comments are preceded by the // symbol and have no terminator symbol. Line comments end at the next line break and are useful for describing the use of variables, leaving quick notes on program flow within functions, and for debugging purposes.

Following is an example showing both types of comments:

<html>

  <head>
    <title>
      JavaScript Professional Projects - Comments
    </title>

    <script language="JavaScript">
    <!--
      /*
          This is a block comment. You should place these
          before each function you write to give the reader
          an idea of what it does.

          All text in this type of comment is ignored by the
          interpreter - including JavaScript commands!
      */
      function prototype()
      {
        // This is a one line comment
        // These comments are used to explain key steps
        // within a function.
      }
    // -->

    </script>
  </head>

  <body>

    <center>
      <font size=6>JavaScript Professional Projects</font><br>
      <font size=4>Chapter 1: Comments</font>
    </center>

  </body>

</html>

It is a good idea to get in the habit of using comments throughout a program during the coding process. The result of using comments will be a professional-looking and easy-to-maintain source program.

White Space and Line Breaks

The browser ignores all white space—including normal spaces, tabs, and line breaks,—during interpretation. The only exception to that rule is white space that is part of a literal. White space is used purely for aesthetic reasons, but even though white space has no direct effect on the execution of a program, it is still very important. A well-formatted source file will drastically increase the readability of a program and make maintaining it much less of a chore.

Following is an example of code without enough white space:

<html>

  <head>
    <title>
      JavaScript Professional Projects - White Space and Line Breaks
    </title>

  </head>

  <body>

    <center>
      <font size=6>JavaScript Professional Projects</font><br>
      <font size=4>Chapter 1: White Space and Line Breaks</font>

    </center>

    <br><br>

    <p>
    A poorly formatted function can be difficult to read and
    difficult to debug.&nbsp; Here is an example of a poorly
    formatted function:<br><br>
    <font face="Courier New">
    function f1(var1,var2,var3){var answer;<br>
    answer = 0; for( i = 0;<br>
      &nbsp;i < 10 ; i = i +1 ){<br>
        &nbsp;&nbsp;&nbsp;answer = answer + var1;<br>
      &nbsp;answer *= var2;<br>
    answer--;<br>
    }<br>
      &nbsp;return(answer-var3);<br>
      &nbsp;}<br>
    </font>
    <br>
    This function does work, but it's not pretty.<br><br>
    A much better way to write the same function would
    be like this:<br><br>
    <font face="Courier New">
    function f2( var1, var2, var3 )<br><BR>
    {<br>
      &nbsp; var answer = 0;<br>
      &nbsp; for( i = 0 ; i < 10 ; i = i + 1 )<br>
      &nbsp; {<br>
        &nbsp;&nbsp;&nbsp; answer = answer + var1;<br>
        &nbsp;&nbsp;&nbsp; answer = answer * var2;<br>
        &nbsp;&nbsp;&nbsp; answer--;<br>
      &nbsp; }<br>
      &nbsp; return( answer - var3 );<br>
    }<br>
    </font>
    <br>

    Although the extra spaces and line breaks will add slightly
    to the download time, it will add greatly to the readability
    and ease of updating.
    </p>

  </body>

</html>

During the life cycle of a program it will constantly be changed and updated. In most cases either you or someone else will have to go back and debug, rewrite, or make additions to the code you have written. It will be much easier and more efficient to do so if the original code has made good use of white space for clean, easy-to read formatting.

Optional Semicolon

Unlike in languages such as C, C++, and Java, the semicolon at the end of some JavaScript code lines is not necessary. The semicolon in JavaScript is used more for separation rather than termination. Because this is the case, you need not place a semicolon at the end of a single line of code. A semicolon is required, however, when there are two or more consecutive JavaScript statements in the same code block - such as a function.

At that time, it is common practice to place the semicolon at the end of the preceding line of code.

This example demonstrates some of the places a semicolon would and would not be needed:

<html>

  <head>

    <title>
      JavaScript Professional Projects - Comments
    </title>
    <script language="JavaScript">
      /*
         This function demonstrates an example where a
         semicolon is not needed.
      */
      function sayHello()
      {
        alert( "Hello visitor!" )

      }

      /* 
         This function demonstrates an example where a
         semicolon is required.
      */
      function getDate()
      {
        var today = new Date();
        return( today )
      }
    </script>
  </head>

  <body onLoad="JavaScript: sayHello()">

    <center>
      <font size=6>JavaScript Professional Projects</font><br>
      <font size=4>Chapter 1: Optional Semicolon</font>
    </center>

    <br><br>
    <p>
    Today's date is
    <script language="JavaScript">
    <!--
      document.write( getDate() );
    // -->
    </script>
    . Have a nice day!

  </body>

</html>

Even though the semicolon is not always required, it is a good idea to get in the habit of using it. Doing so will avoid complications later on. If you were to make additions to a Web page and forgot to place a semicolon at the end of the old lines of code before adding new lines, the result would be some very confusing error messages.


Team LiB
Previous Section Next Section