HTML Markup | JavaScript | Java | Home & Links

Tutorial 1 - Structure / Syntax

JavaScript applications are based on a structure and syntax common to many languages (eg C, JavaScript, awk, perl). This makes it easy to cross over from one language to another based on program requirements, resources and politics. ECMA-262 is the defining JavaScript standard.

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 are temporary data holders. Variable names are identifiers. Variables are declared with the reserved word var. JavaScript is a loosely-typed language as a variable uses a datatype depending on its currently 'assigned' value. 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. 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).

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


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
// Set up array of month Names

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.

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

var xmas=[]; // next tray

var rr=[]; // next tray

var trays=[]; // trays global
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.


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:2016 01 26]