HTML Markup | JavaScript | Java | Home & Links

Tutorial 1 - Structure / Syntax

JavaScript, like many languages (eg C, Java, awk, perl) is based on a common syntax and structure. This makes it easy to move from one language to another based on program requirements, resources and politics. ECMA-262 is the defining JavaScript standard. This tutorial on syntax and structure (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 basic rules that define the tokens or basic atoms of the program. It is the lowest level syntax of a language and specifies what is punctuation, reserved words, identifiers, constants and operators. Some of the rules are:

Literal Constants

Literal constants are values that do not change within a program. Some types of literal constants are:

Note: Floating point numbers less than one should begin with a leading zero. For example write 0.1 rather than .1

Note: Do not use leading zeros to format integers as this may give an unintended octal meaning. Use spaces instead!

Warning: If a number begins with two zeros and contains a decimal point (eg. 005.3) it will generate an error. Techniques to guard against this type of error are discussed in validation.

Question: WHY can one use either kind of quote marks (they must match however) when defining a STRING value?
Answer: Occasionally there is a need to have a string that uses internal quotation marks or a possessive form or a contraction (apostrophe). To handle one of these situations, bracket the string with the opposite form of quote.

Escape sequences are used inside literal strings to allow print formatting as well as preventing certain characters from causing interpretation errors. Each escape sequence starts with a backslash. The available sequences are:

SeqUsage SeqUsage
\bbackspace \\backslash
\fformfeed \"double quote
\nnewline \'single quote
\rcarriage return \###Octal encoded character
\thorizontal tab \uHHHHUnicode encoded character

Variables

Variables are temporary data holders. Variable names are identifiers. Variables are declared with the reserved word var. At the same time variables are declared they may be assigned or take on a value of boolean, numeric string, object, undefined or null type. JavaScript is a loosely typed language as a variable can take on a different type later in the script depending on its currently '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
signalFlag=true;  // boolean [true or false]
counter=1;        // numeric [values ± 2>sup>53>/sup>]
firstName='fred'; // string using single quotes
lastName="fred";  // string using double quotes

For logical testing purposes, loosely-typed variables can be thought of as either truthy (true, non-zero numbers, non-empty strings, Infinity, -Infinity) or falsey (false, the number 0, empty strings, NaN, null, undefined).

Beware: Quirks in MSIE cause problems when a tag id is reused as a variable. Always use var to assign a variable.

Note: Some functions limit use of numerics to ± 231. Either test the function or limit all numbers.

Arrays

Arrays allow storage of several related values in the same variable (eg. a set of marks). Arrays are created with the literal constructor.

myArray=[]; // null literal array
myDataArray=[25,30,22,10]; // array with values

An example that shows how days and months can be displayed as text rather than as numbers is:

// Set up array of day Names
dayNames=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday',
   'Saturday'];
// Set up array of month Names
monthNames=['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 positive integer number in square brackets. For example, dayNames[0] returns the value Sunday. The array name by itself returns the full array (ie. all values). Use the length property to return the number of items in an array. For example, monthNames.length returns the value 12. To copy a complete array use the slice() method.

a=[1,2,3]; b=a; a[0]=7; // passes pointer only
document.writeln(a+' '+b+'<br>');
a=[1,2,3]; b=a.slice(); a[0]=7; // passes data
document.writeln(a+' '+b+'<br>');

ADVANCED TOPIC: Multiple dimension arrays can be set up as an array of arrays.

array0=['fred', 'ethel', 'ricky', 'lucy']; // people
array1=['65', '60' , '33', '31'];   // ages
arrayArray=[array0, array1]; // two dimensioned array of above
alert(arrayArray[0][3]); // shows array access

ADVANCED TOPIC: Associative arrays are arrays indexed by string values rather than positive integers.

aa=[]; // define the array
aa["A"]=90; aa["B"]=80;
aa["C"]=65; aa["D"]=50; aa["F"]=0;
alert(aa["C"]); // reference a value

Values are accessed in the usual manner. And to get a full display of the entire array, use the for/in construct.

text="";
for (prop in aa) {text += prop + ': ' + aa[prop] + ' \n';}
alert (text);

ADVANCED TOPIC: Multiple dimension associative arrays are set up similarly to regular arrays. An example using trays of slide images is as follows

var family=[]; // first slide tray
family[0]='mom.jpg^^*';family[1]='pop.jpg^^*';family[2]='adam.jpg^^*';
family[3]='betty.jpg^^*';family[4]='fido.jpg^^*';

var xmas=[]; // next tray
xmas[0]='tree2007.png^^*';xmas[1]='uncleFred.png^^*';
xmas[2]='auntEthel.png^^*';

var rr=[]; // next tray
rr[0]="b9_cafe.jpg^^*";rr[1]="doodlebug.jpg^^*";
rr[2]="freight2.jpg^^*";rr[3]="freight.jpg^^*";

var trays=[]; // global for all trays
trays['family']=family; trays['xmas']=vAds;
trays['rrAds']=rr; // indexName is not always same as arrayName

Operators and Expressions

Operators are actions that manipulate, combine or compare variables. They fall into several categories as follows:

Assignment:            = += -= *= /= %=
Arithmetic:            + - * / % (modulus) ++ (increment) -- (decrement)
String Concatenation:  +
Comparison-Relational: > >= < <=
Comparison-Equality:   == !=
Comparison-Identity:   === !==
Note: Use the Identity form when type coercion is not wanted
      before a comparison! (eg true, false, null or "")
Bitwise Comparison:    & | ^ ~ - << >> >>>
Boolean Comparison:    && || !
Object Creation:       new
Object Class Test:     instanceof
Miscellaneous:         delete typeof void (returns undefined)
Ternary:               ? (eg (bVal) ? tExpr : fExpr)

The logical-and operator (&&) returns a value (not necessarily true or false). If A is true, A && B evaluates to B. If A is false, A && B evaluates to A. It's short circuit logic. If A is false, B isn't even evaluated.

The logical-or operator (||) is similar. A || B evaluates to A if A evaluates to true and to B if A evaluates to false.

Note: Although JavaScript is a loosely-typed language, there are times to force or coerce a specific type to a variable by casting its type. A clean way of doing this is with object constructors. For example Number(x) and String(x) are explicit casts of the variable x.

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.

Statements and Blocks

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, it is good coding practice to put it in explicitly!

Declaration statements reserve an identifier for referencing a value. They can optionally begin with the var keyword and/or optionally assign an initial value. For example:

var thisCar;
thisTruck="Mazda B2000";

Assignment statements use an assignment operator to store a value or the result of an expression in a variable.

firstName="Fred";

Blocks are sets or lists of statements enclosed in curly brackets. Blocks are normally treated as units. In JavaScript, blocks do not give variables scope.



JR's HomePage | Comments [jstutor1.htm:2014 08 25]