# Tutorial 3 - Core Language Tutorial 2 - Objects,Events&Functions - Tutorial 4 - Working with Forms JavaScript like many languages (eg C, Java, awk, perl) is based on a common syntax and grammar developed by the Bell Labs in the 60's. This makes it easy to cross over from one language to another based on program requirements, resources and politics. This tutorial on JavaScript syntax and grammar (ie. programming in the small) assumes introductory programming experience in another language and includes the following topics: ## Lexical Structure The lexical structure of a programming language is the set of elementary rules that specify how you write a program. It is the lowest level syntax of a language and specifies such things as what identifier names look like. Some of the basic rules for JavaScript are: JavaScript is case sensitive. Whitespace, tabs, and newline characters are ignored except when part of string constants. Whitespace can be added as needed for readability. Block comments begin with /* and end with */ [preferred over single liners] Single line comments begin with // Identifiers are names for variables, functions and loop labels. The first character must be an ASCII letter, underscore or dollar sign. Following characters can also include digits. Letters are A to Z and a to z. Note: An identifier must NOT be any word contained in the JavaScript Reserved Word List Reserved words (or keywords) have special meanings within the language syntax. Check the JavaScript Reserved Word List for a complete listing. Statements terminate in semicolons! Make sure to always terminate statements with a semicolon. ## Literals or Constants Literals (or constants) are values that do not change within a program. Some types of literals and examples are: Boolean: true, false Numeric 5, 0xFF (hexadecimal), 2.543, 8e12, -4.1E-6 String: 'fred', "Fred and Ethel" Primitive: Infinity, NaN, null, undefined One question that is often asked is 'WHY can one use either kind of quote marks (they must match however) when defining a STRING value?' The answer lies in the fact that you may need to have a string that uses a possessive form or contraction (apostrophe) or an internal quote. To handle either situation bracket the string with the opposite form of quote Note: Floating point numbers less than one should begin with a leading zero. For example write 0.1 rather than .1 Warning: If a number begins with two zeros and contains a decimal point (eg. 005.3) it will generate an error. Validation techniques to guard against this type of error will be discussed in Getting the Bugs Out. ## Escape Characters Escape characters are used inside literal strings to allow print formatting as well as preventing certain characters from causing interpretation errors. Each escape character starts with a backslash. The available character sequences are:
Seq | Name | Seq | Name
--- | --- | --- | ---
\b | backspace | \f | formfeed
\t | horizontal tab | \" | double quote
\n | newline | \' | single quote
\r | carriage return | \\ | backslash
\### | Latin encoded character | \uHHHH | Unicode encoded character
## Variables Variables are temporary data holders. Variable names (or identifiers) must begin with a letter, underscore or dollarsign, use ASCII characters and underscore only, and are case sensitive. They can not be one of the JavaScript reserved words. Variables are declared with the reserved word var. At the same time variables are declared they may or may not be assigned or take on a value of boolean, numeric or string type. JavaScript is said to be a loosely typed language as the variable can take on a different type later in the script depending on its 'assigned' value. Variables have scope, ie. they are either global (defined outside any function) or local to the function they are defined within).
    var name;                /* variable created but undefined */
    var signal_flag = true;  /* boolean */
    var counter = 1;         /* numeric */
    var first_name = 'fred'; /* string using single quotes */
    var last_name = "fred";  /* string using double quotes */
## Arrays Arrays allow you to store several related values in the same variable (eg. a set of marks). One example that shows how days and months can be displayed in text rather than numeric form is:
    // Set up array of day Names
    var dayNames=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday',
        'Friday','Saturday');
    // Set up array of month Names
    var monthNames=new Array('January','February','March','April','May',
        'June','July','August','September','October','November','December');
To access an individual value in an array use the array name followed by an indexing number in square brackets. The array name by itself will return the full array (ie. all values). If you ever need to know how many items are contained in an array, use the length property (eg. monthNames.length would return the value 12). ADVANCED TOPIC: Multiple dimension arrays can be set up as an array of arrays.
    array1 = new Array ('fred', 'ethel', 'ricky', 'lucy');   // people
    array2 = new Array ('65', '60' , '33', '31');   // ages
    arrayArray = new Array (array1, array2); // two dimensioned array of above

    alert(arrayArray[0][3]); // shows array access
ADVANCED TOPIC: Associative arrays can be faked by using the Object object.
    var aa=Object();
    aa["red"] = "red";  // if you like bracket style
    aa.size = 15;       // if you like object style
You can access the values in the usual manner. And to get a full display of the entire array you can use the for/in construct.
    text = "";
    for (prop in aa) {
        text += prop + ': ' + aa.prop; + '\';
        }
    alert (text);
## Operators Operators are actions that manipulate, combine or compare variables. They fall into several categories as follows: Arithmetic: + - * / % (modulus) ++ (increment) -- (decrement) String Concatenation: + Assignment: = Advanced Assignment: += -= *= /= %= Comparison: == != > >= < <= Identity: === !== Note: Use this form when type conversion is unwanted before comparison! (eg true, false, null or "") Logical: && || ! Bitwise: & | ^ ~ - << >> >>> Conditional: ? (eg. ans = (w<x) ? trueval : falseval ) Typeof: typeof Object specific: new, delete Void: void [returns undefined regardless of expression] ## Expressions and Conditions Expressions are used to combine two or more values using operators to create a new value. One example is x + y which will add the two values together if they are numeric or catenate or join them together if they are strings. Conditions compare two values (often as variables) and return either a true or a false value. An example is "does x equal 9". In JavaScript the condition is surrounded by round brackets and expressed in logical terms (x == 9) note the double equal!. ## Statements Statements are complete program instructions made from constants, variables, expressions and conditions. Statements always end with a semicolon. A program contains one or more statements. Although most interpreters assume a semicolon at the end of a line, a good coding practice is to make sure you put it in explicitly! Blocks are sets or lists of assignment statements enclosed in curly brackets. Blocks are normally treated as units. Variable statements assign a named placeholder for referencing a value. The variable statement can optionally assign an initial value as well. For example:
    var this_car;
    var this_truck = "Mazda B2000";
Assignment statements use an assignment operator to store a value or the result of an expression in a variable.
    first_name = "Fred";
Conditional statements execute a set of other statements only if certain conditions are met. The condition is always enclosed in round brackets. The statements to be performed if the condition is true are enclosed in blocks (ie curly brackets). For example:
    if (value > 5) { x = 7 }
Occasionally you may want to perform some actions for the false outcome of the condition as well. The else keyword is used to separate branches.
    if (name == "fred") {
         x = 4;
         }
         else {
         x = 20;
         }
NOTE: When the conditional if statement is used only to make an assignment to one variable, you can use the terse C syntax such as:
    x = (name == "fred") ? 4 : 20;
## Loops and Switches While statements allow a set of statements to be repeated or looped through until a certain condition is met. For example to output #1 #2 #3 etc. on separate rows you could write:
    while (i<=5) {
        document.writeln("#"+i);
        i = i + 1;
        }
For statements allow a set of statements to be repeated or looped through a fixed number of times. For example to output #1 #2 #3 etc. on separate rows you could write:
    for (i=1; i<=15; i++) {
        document.writeln("#"+i);
        }
For ... in statements allow looping through all the elements of an array or properties of an object. For example:
    for (var propname in navigator) {
        browser += propname + ": " + navigator[propname] + "\n";
        }
    alert(browser);
would loop through all the navigator object's properties. This can be made into a great exploring tool. Switch (or case) statements are used to select which statements are to be executed depending on a variable's value matching a label.
    yourchoice=window.prompt('pick a number between 1 and 4');
    switch (yourchoice) {
       case '1': alert('you typed a 1'); break;
       case '2': alert('you typed a 2'); break;
       case '3': alert('you typed a 3'); break;
       default: alert('Only 1, 2 or 3 allowed!);
       }
A problem with this example is that there is only one type of error checking done. What if the user had entered a punctuation sign or typed TWO instead. Also this is a forced example as one could have used the variable yourchoice within the alert method and not used a switch statement at all. Think of the example as just a demonstration of how the switch statement is structured. ## Continue, Break and Return Continue statements are used in 'while' or 'for' statements to force another iteration of the loop. The following is a trivial example. Most often the continue is used as part of a conditional statement that only happens in certain cases.
    var x = 0;
    while (x < 10) {
       x++;
       alert(x);
       continue;
       alert('you will never see this alert dialog');
       }
Break statements are used in 'while', 'for' and 'switch' statements to force an abrupt termination or exit from the loop. In the following example the loop is never completed. Once again the normal use of break is as part of a conditional statement.
    var x = 0;
    while (x < 10) {
       x++;
       alert(x);
       break;
       alert('you will never see this alert dialog');
       }
Return statements are used to exit quickly from a function or to to pass values back from the function. Tutorial 2 - Objects,Events&Functions - Tutorial 4 - Working with Forms Copyright (c) 2005 by John W. M. Russell