Syntax

main > javascript > core javascript > js syntax

These tutorials are about JavaScript and its use for ViSTA programming.

Yes, the somewhat askew formatting of this page is intentional.

The Syntax of JavaScript

syntax: the rules that define the form of a given language

Every language has a syntax, the rules according to which it is written. There are numerous other ways of talking about syntax, and you may hear it referred to as lexical structure, or grammar, which, if you are a linguist, are terms that means specific things. We are not linguists, we are learning to program, so we are going to make pretend the words are synonymous and talk about them all as syntax.

If you ever move on into a Ph.D. in computer science, then you can worry about the finer points of linguistic terminology as applied to computer languages.

statement: a piece of computer code that accomplishes a single task

First off, as with most any programming language, JavaScript is made up of a collection of commands called statements. A statement is a piece of code or set of commands that accomplishes a single task.

A simple statement is normally a single command, such as
a = b + c;.

A compound statement is a statement that requires multiple commands to define, for instance
if (x == 1) { y = 2; }.

If you group a collection of statements together to be executed as a unit, this is normally referred to as a function.

The Character Set

JavaScript programs are written using the Unicode character set. Unicode is a 16-bit character set that has space to represent pretty much every character in every known human language. This means that JavaScript uses two bytes to represent every character in a string instead of one. Most of us are used to working in ASCII, which is a 8-bit encoding language that only uses one byte for each character.

Since older version of JavaScript do still use ASCII, and since this is all transparent to you anyway, unless you are actively trying to code in Unicode, it is not normally something you have to worry about in day to day coding. Nonetheless, it is something that you should be aware of.

Case Sensitivity

JavaScript is case sensitive.

This means that you have to be aware of whether or not things are capitalized. By default, just about every JavaScript command you will have to deal with is lowercase. Thus, while is a valid command, but WHILE is not.

HTML, on the other hand, is not case sensitive. Therefore, what you may type in HTML may have a different case in JavaScript. for instance, an event handler may be called onClick in HTML, but onclick in JavaScript. The good news, if you use XHTML, is that XHTML is also case sensitive, and like JavaScript uses lowercase for almost everything. What is onclick in JavaScript is also onclick in XHTML.

When working with style rules and JavaScript, things get a little more complicated. A style property named background-color would be read by JavaScript as "subtract the value of the variable color from the value of the variable background." This is probably not what you wanted when trying to use JavaScript to change the background color of the document.

Hyphenated keywords from other languages that need to be addressed in JavaScript are written C-style, run together without hyphens and with the first letter of every word after the first on capitalized. For instance,
border-left-color (CSS)
would be written as
borderLeftColor (JavaScript).

All browser and document object properties are also case sensitive, so if you are having problems, make sure you have matched case exactly.

White Space

JavaScript is relatively insensitive to white space and line breaks in the code. This means that you are free to format the code as you see fit, hopefully organizing it into a structure that is easier to read and maintain.

Although you can put white space and line breaks between things, you should not put then within things.

Anything that is a token, or single coding element, cannot be broken up. For instance, the number 123 cannot be written 12 3.

You also cannot have line-breaks inside text strings literals. If you need to run a text string across multiple lines, you should break the string into multiple tokens and use a concatenation operator to string it together.

 Wrong:
var someString = 'Some really long
  quote that goes on for more than
  one line, and just seems totally
  uninclined to end.';

 Right:
var someString = 'Some really long ' +
  'quote that goes on for more than ' +
  'one line, and just seems totally ' +
  'uninclined to end.';

Since we are on the topic, I should point out that at times I cannot fit the code I am trying to present on one line when providing coding examples. Since I want the code to fit into a tight enough space to fit on a small computer screen, I have to break lines of code at times in the examples. When I break code across lines in the example that wouldn't really be broken across line, there will be a little arrow ( » ) indiscating that the line is a continuation of the line above it and that there really should not be a line break there.

What you will see:
var someString = 'Some really long
» quote that goes on for more than
» one line, and just seems totally
» uninclined to end.';

 It is not the same thing as this:
var someString = 'Some really long
  quote that goes on for more than
  one line, and just seems totally
  uninclined to end.';

 It is the same thing as this:
var someString = 'Some really long quote that goes on for more than one line, and just seems totally uninclined to end.';

As you can see, it would be a real pain to work with these pages if I did not break up really long strings. It would also be impossible to print them, because the ends of everything would get truncated. So just remember that a green arrow is a continuation arrow that says there really is no line break at this point, so don't include one. This is a common presentation method in most textbooks so I have chosen to stick with it.

I can promise you that many people in my classes are going to fail to heed this warning and it is going to mess them up. Especially those who think they can just cut and paste everything from my notes and it will somehow magically work.

The Semi-Colon

All JavaScript statements end in semi-colons ( ; ), except, of course, for those that don't.

Seriously, just assume that all statements end in a semi-colon, but be aware of two things:

The first is that JavaScript does not require a semi-colon at the end of a statement that ends at the end of the line. This is to say that if you have one statement per line, then you don't need semi-colons. Skipping them however make your code harder to read and to debug, so you should use semi-colons anyway.

The real problem with this "convenient" feature is that if your statement runs across many lines, JavaScript may think the command ended at the end of the line. For instance, what would the following function return?

function sample( ) {
  var a = 1;
  var b = 2;
  var c = 3;
  return
    a + b + c;
  }

Assuming that the function ran successfully, it would return true, not 6, which is what the code seems to imply. What JavaScript sees is:

function sample( ) {
  var a = 1;
  var b = 2;
  var c = 3;
  return;
  a + b + c;
  }

The practical upshot of this is always be careful about where you break your statements if you break them across multiple lines.

For instance, if we go back to our string example earlier, if put the plus signs on the wrong place, JavaScript will not realize that the string continues on the next line.

 Wrong:
var someString = 'Some really long '
  + 'quote that goes on for more than '
  + 'one line, and just seems totally '
  + 'uninclined to end.';

 Right:
var someString = 'Some really long ' +
  'quote that goes on for more than ' +
  'one line, and just seems totally ' +
  'uninclined to end.';

The second thing to be aware of is that any statement, such as a function, that ends in a curly bracket does not need a semi-colon after the bracket. In this case the bracket serves to end the statment.

Putting a semi-colon after a curly bracket creates an additional empty statement, which does nothing. It won't do any harm, but it will waste a computing cycle or two to interpret and process the nothing.

Comments

JavaScript comments work just like C and C++ comments. You can use the double-slash comment ( // ) for single line comments, or the slashterisk comment ( /* */ )for multi-line comments.

// This is a single line comment

/* This is a multiple line comment
 * possessed of both an opening and
 * a closing bracket */

JavaScript also has to deal with HTML style comments, since it occurs in HTML documents. In particular, you should comment out your inline code so that HTML browsers which don't understand JavaScript don't try to render it as content.

You can also use HTML comments in JavaScript, but it will treat them differently than you might expect.

JavaScript treats the string <!-- as a marker indicating the beginning of a single line comment. However, it does not recognize the close tag (-->) and will try to read is as a JavaScript command (you cannot, however, decrement the greater-than comparison operator). In order to avoid this you should comment out the close comment mark.

 Right:
<script>
<!-- hide from old browsers
  (JavaScript code goes here)
// stop hiding the script -->
</script>

 Wrong:
<script>
<!-- hide from old browsers
  (JavaScript code goes here)
-->
</script>

 Also Wrong:
<script>
<!-- function someFunc() {
  (function code goes here)
  }
// -->
</script>

In the last instance above, the first line of code is commented out because it occurs on the same line as the comment marker.

Literals

literal: a data value that appears as itself in a program

A literal is a data value that appears as itself in a program. For instance, the number 123 or the text-string 'abc'.

Numeric literals are written as themselves.

String literals must appear in balanced quotes. Balanced quotes means that the string must start and end with the same type of quote mark. Smartquotes, which are generated by many word processors, are also not allowed.

 Valid string literals
"a"
'qwerty'
'123abc'

 Invalid string literals
// unbalanced quotes
"abc'
// smart quotes
// note the angles of the quote marks
// and how they mirror each other
‘abc’
“abc”

There are also keyword literals in JavaScript which do not need quotes, such as null. We will discuss literals in more detail when we talk about variables and data.

Identifiers

identifier: the name assigned to a variable to store data values

An Identifier is the name assigned to a variable used to store some data value. Variables are named locations in memory thar can store simple values such as strings and numbers, or they can be names that are assigned to functions in the code. Yes, we tend to think of variables as different from functions, but the computer doesn't.

There are just a few rules for identifier names in JavaScript.

All identifiers must begin with a letter, an underscore ( _ ), or a dollar sign ( $ ).

Identifiers cannot begin with a space. This is obvious enough since the name doesn't start until the spaces end, but the other characters not allowed may need a little explanation. You don't want to use special characters that are operators, such as + or - since JavaScript will to apply the operation to the identifier. That makes sense. Numbers also cannot be used because JavaScript assumes that anything that starts with a number is a number, a numeric literal. More on that later.

All characters after the first character may be letters, numbers, an underscore ( _ ), or a dollar sign ( $ ).

Once you have established that the identifier is an indentifier, you can use numbers within the name.

All characters should be valid ASCII characters.

Even though JavaScript uses Unicode, for backward compatability, it is a good idea to stick with the ASCII character set.

Identifiers cannot be the same as any JavaScript reserved words.

You cannot use a name that JavaScript is already using for something else. You don't want to name a variable if or break, since those words already have another meaning. Depending on context, you will either invoke the command instead of declaring the variable, or actually create a variable of that name which means the command will no longer exist, its function value having been replaced by whatever you assigned to it. You should also avoid names that are used within pre-defined objects.

This is a partial list of the JavaScript reserved words:

break         for           throw
case          function      true
catch         if            try
continue      in            typeof
default       instanceof    var
delete        new           void
do            null          while
else          return        with
false         switch
finally       this