It is very strict and imposes style conventions in addition to syntax. I set the
following options to remove "errors" that are not errors.
a browser — true — Otherwise get errors saying
undefined variable.
missing 'use strict' pragma — accept missing the
strict pragma in all functions
many var statements per function
Messy white space — true — ignores your layout style
Javascript console
Use the function console.log(String); to log messages to the
Javascript console. To activate the console use the following.
Firefox — Tools --> Web Developer --> Web Console
Chrome — Tools --> Javascript Console
Internet Explorer — F12 key gets the Developer Tools, then
select the console tab
Safari — Develop --> Show Error Console. You may need to
turn on the Developer menu, in which case, Safari --> Preferences, click
the Advanced button, and turn on the "Show Develop menu in menu bar"
checkbox.
Script element
SCRIPT elements can appear in the following locations.
In the HEAD element — statements not within functions execute
during script load.
In the BODY element — statements not within functions execute
during script load.
<script> … Javascript statements … </script>
SCRIPT elements in the HEAD are loaded before the contents of the page is
loaded. SCRIPT elements in the BODY are loaded when they are encountered, as
a consequence, it is frequently the case that the last tag in the BODY is
a SCRIPT tag wherein the Javascript modifies the contents of the fully loaded
page.
Variables — Program memory
Memory is represented by a collection of boxes, called variables, that
contain data.
Every variable has a unique name and an associated type.
Every type as an associated list of operations. E.g. numbers have arithmetic
and comparison operations.
The variable document represents the web page in which the Javascript
program is executed.
Every element in a document has a name or can be given a name.
As a consequence every element is also a Javascript variable
document.calculator
is the form element within the document that
represents the simple calculator.
document.calculator.result
is the result textfield in the form
document.calculator.result.value
is the contents of the result textfield in the form
The value of every variable can be both read from and written to.
Variable scope
Variables can have global and local scope
Local variable
Declared within a function, referenceable (visible) only within
the function
Global variable
Declared outside of a function,
referenceable (visible) everywhere within a script.
Types of variables
Variables are objects with properties depending upon their type. The following
lists the types of variables in Javascript.
Standard arithmetic plus a small library of mathematical functions defined
as a math object.
here are the functions: Math.random(),
Math.min(...), Math.max(...),
Math.round(...),
Math.ceil(...), and Math.floor(...).
There constants: Math.E,
Math.PI, Math.SQRT2,
Math.LN2, Math.LN10,
MATH.LOG10E, and Math.LOG2E
The most common string operators are used to join strings, split strings,
extract substrings, and search.
Join strings
The + operator is used to join strings. Result = "Item_1 " + "Item_2" + " Item_3";
Result is a string with the following value. Result = "Item_1 Item_2 Item_3"
Split a string
Split a string into an array of substrings where a separator string
is used to partition the string into substrings. Result = "Item_1 Item_2 Item_2".split(" ");
Result is an array with the following value. Result[0] = "Item_1"
Result[1] = "Item_2"
Result[3] = "Item_3"
Extract a substring
Extract
the substring of characters string[index_from .. index_from + length − 1]
var Result = string.substring(index_from, length);
Result = "12345678".substring(2,4) gives
Result = "3456" — recall that numbering
starts at 0.
Boolean
Logical operators
Array
1-d array
— can fake higher-d by storing and array as a
value but have to extract the value to reference an item within it
Can use a list to initialize an array — new Array(1,2,3)
— theArray = [1,2,3]
The operations push (optionally with multiple arguments) and pop
are used to add and remove items from the "high" end of the
array
Object literals
— they are also called tuples and records.
They are analogous to structs in C
and classes with only attributes in C++, Java, and Eiffel.
Example: An object literal is created and written to the
web pag.
Object classes
Classes are functions with attributes as the
variables in the function. The following example shows the preferred
way of dealing with object classes.
Example creates true static and instance functions.
this — reference (pointer) to the current object
typeof(), undefined and null types
Javascript is an untyped language; i.e. a variable can be assigned a value
of any type at any time. However, operations are specific to particular types.
As a consequence, it is necessary, in some circumstances, to verify the
type of a variable to ensure it is of the correct type for the operations that
need to be done.
if (typeof(aVariable) == "number") { /* doing arithmetic is safe */ }
else { /* Not safe to do arithmetic */ }
The function typeof(variable) returns a string containing the
type of the variable where the return type is one of the following.
number
string
boolean
object
Undefined — a variable that is declared but is not given a value
is of type undefined
Null — assigning the value null to an variable (var x123 = null)
makes the variable to be of type object with no value.
Datatype conversion
Number value
integers and real numbers (floating point) are just
number. In general you need to convert a number to the "type" you
want. For example use Math.round(variable) to convert a real number
to an integer number.
The Number(variable) function converts the value of the variable to
a number. If there is no corresponding number, the value NaN (not a
number) is returned.
String value
A number is converted to a string value by "adding" the number to
a string newString = oldString + 5 converts the 5 to a string
and appends it to oldString
The operation toString() converts a number to a string var number = 19;
var numberAsString = number.toString();
Program statements
Program statements correspond to sentences in a language. Some sentences
have a simple structure and some have a complex structure.
Assignment statement
variable = expression;
The expression reads the values of variables and combines them according
to the operations in the expression, and then stores the resulting value
in the variable on the right of the equal sign.
a = 3 + 4*(5-7).
b = 3 * a.
Function call
functionName(argument_list)
A preexisting set of instructions with the name "functionName" is executed
using the information given in the argument_list). In the first example
alert is the functionName and "The network is down" is the
single argument given to the function. Changing the argument list will
result in similar but different output.
// Display The network is down on the screen.
window.alert("The network is down");
// Display Please enter a number on the screen.
window.alert("Please enter a number");
// Display Line 51 has an error on the screen.
window.alert("Line 51 has an error");
All arguments are optional
Can nest function defintions: inner ones are hidden (private)
Methods: Static and Instance
The prompt and confirm popup boxes
With the window.prompt("prompt message") operation the user can enter data
in a popup box.
When cancel is pressed the value null is returned. When OK is pressed the
entered data string is returned.
With the window.confirm("confirm message") operation the user can press Cancel,
whereupon the value true is returned, or the user can press OK, whereupon
the value false is returned.
Control structures
There are three types control structures in writing a program in any
language.
A sequence of statements
There is no special syntax. In all languages it consists of writing
one statement after another.
A choice of statements
In Javascript there are two structures that deal with choice.
if … then … else
if (condition) {
then phrase statements
}
else {
else phrase statements
}
Switch statement, written in Javascript as follows
switch(n) { // n is typically an integer, character or string
case n_value_1: case statements; break;
case n_value_2: case statements; break;
default: default statements;
}
In javascript there are four different loop structures. Each one
is the best one to use in some circumstances.
Standard for loop
Good to use when you can count either up or down and will terminate
when the counter reaches an appropriate value; i.e. you know
ahead of time the number of times you need to go around the loop.
For example processing the elements of an array or list.
for (initialize loop variable ;
end test for loop variable ;
increment/decrement loop variable) {
loop body statements
}
Example 1: process a list of arguments with two algorithms, one is
incorrect, while the second is correct but a poor design.
Example 2: process a list of arguments with two algorithms, one is
correct but a poor design (second algorithm in example 1), while the
second is correct and a good design.
while loop
Go around the loop zero or more times.
Good to use when you do not know ahead of time how many times
you may have to go around a loop. For example: in a game
loop until you find a good move, where the body of the loop
explores different moves, rates them and the loop exits when
a good enough move is found.
while (continue condition) {
loop body statements
}
do-while loop
Go around the loop one or more times.
Use in situations simlar to the while loop, except you must
be happy to go around the loop at least once.
do {
loop body statements
} while (continue condition);
for-in loop
In Javascript use this loop for lists of property-value pairs. For example:
the list of components of an object literal; the list of
property-value pairs in a style definition; the list of attributes for
an HTML element.
for (variable in collection) {
statements using the variable
}
program text (could be empty) /* a comment *//* block comment can go
over lines */
To end of line comment
program_text (could be empty) // comment ends at the end of this line
more program text
Writing to HTML elements
Javascript can write an HTML element to a page. We will look at this
in more detail when we discuss the DOM model (Domain Object
Model). For now here are typical statements to use.
Add a new element
Adds the element to the page at the point at which the function
is called.
document.write("<p>A new paragraph added to the page");
Change the contents of an element
Find the element by its id then change its contents.
Syntax — typically mistyping: wrong case; missing bracket
Interpreted — misunderstanding what operations do; e.g. for-in
returns the index of an array as a string, not a number, and you may be
expecting the value to be returned
Runtime — user types an incorrect value, network goes down, web
pages move, browser may not interpret some Javascript
Semantic — you have used incorrect logic
Error types
EvalError — misusing the eval() operation
RangeError — number is outside of its valid range; division by 0
ReferenceError — object does not exist;
e.g. mistyping a variable name in a statement that differs from its
declaration
SyntaxError — Javascript finds errors in parsing your program text
TypeError — doing operations on the wrong type of data
URIError — web site is down, page does not exist, encodeURI() and
decodeURI() operations are incorrecty used.