Tutorial 2 - Syntax and Grammar
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 define what are the tokens or basic atoms of the program. It is the lowest level syntax of a language and specifies what is punctuation, reserved words, constants, identifiers and operators. 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. They can be added as needed for readability.
- Single line comments begin with //
- Multiline comments begin with /* and end with */
- Statements terminate in semicolons! Make sure to always terminate statements with a semicolon.
- Commas are used to separate words in a list
- Round brackets are used for operator precedence and argument lists.
- Square brackets are used for arrays and square bracket notation.
- Curly or brace brackets are used for blocks.
- Keywords are reserved words that have special meanings within the language syntax.
- Identifiers are names for constants, variables, functions,
loop labels, objects and classes. The first character must be an ASCII
letter, underscore or dollar sign. Following characters can also include
digits. JavaScript style begin class identifiers with a capital letter,
uppercase constant ids and lowercase variables.
Note: An identifier must NOT be any word on the JavaScript Reserved Word List.
Literal Constants
Literal constants are values that do not change within a program. Some types of literal constants are:
- Boolean: true, false
- Numeric 5, 2.543, 8e12, -4.1E-6, 073 [leading zero] (octal), 0xFF (hexadecimal)
- String: 'fred', "Fred and Ethel"
- Primitive: Infinity, NaN, null, undefined
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. Validation techniques to guard against this type of error will be discussed in Getting the Bugs Out.
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:
| Seq | Usage | Seq | Usage |
|---|---|---|---|
| \b | backspace | \\ | backslash |
| \f | formfeed | \" | double quote |
| \n | newline | \' | single quote |
| \r | carriage return | \### | Octal encoded character |
| \t | horizontal tab | \uHHHH | Unicode encoded character |
Variables
Variables are temporary data holders. Variable names are identifiers. Variables are declared with the reserved word var (optional). At the same time variables are declared they may be assigned or take on a value of boolean, numeric or string 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 */ counter = 1; /* numeric */ 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) or falsey (false, the number 0, empty strings).
Note: Although const is a 'reserved word' in ECMA-262 - Edition 3.0 that allows setting a variable as read-only, it will be deleted from Edition 3.1. Const has not been implemented in all browsers. Do not use this construct!
Arrays
Arrays allows storage of several related values in the same variable (eg. a set of marks). Arrays are created with either the literal constructor or the new operator and Array constructor.
myArray = []; // null literal array [Best Practice] myDataArray=[25,30,22,10]; // array with values [Best Practice] myImages = new Array(); // assigns variable name but no content myPics = new Array(10); // assigns space for 10 items myData = new Array(25,30,22,10,5); // assigns data on array creation
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: & | ^ ~ - << >> >>>
Logical Comparison: && || !
Conditional: ? (eg. ans = (w<x) ? trueval : falseval )
Object Creation: new
Object Class Test: instanceof
Miscellaneous: delete typeof void (returns undefined)
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. You can think of && as the guard operator. A && B is then read: A guards B. With the guard operator, if (A) {result=B;}else{result=A;} can be written as: result=A && B;
The logical-or operator (||) is similar. A || B evaluates to A if A evaluates to true and B if A evaluates to false. So || can be thought of as the default operator. It defaults to A, but falls back to B if A is false. So, if (A) {result=A;}else{result=B;} can be written as: result=A || B;
Note: Although JavaScript is a loosely-typed language, there are times you want 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.
Conditions, Statements and Blocks
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 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.