It is very strict and imposes style conventions in addition to syntax.
Check the following option to remove "errors" that are not errors.
a browser — Otherwise get errors saying
undefined variable for some standard browser global variables. You still
need to add var window; as your first statement to make the
window variable available for commands such as window.alert(...);
many var statements per function
Messy white space — ignores your layout style
You should do the followng.
Use spaces and not tabs because tabs do not have a standard definition.
The layout can change with different text editors, display programs and
printing.
Use the following as the first line of every function
"use strict";
Web console
Get the web console with the following.
Use the inspector for finding which HTML elements correspond
to which parts of the HTML file.Use the style editor for prototyping CSS.Use web console with Javascript.
Firefox — Menu Tools --> Web Developer --> Web Console
Submenus of interest
Inspector
Style editor
Web console
Chrome — Tools --> JavaScript Console
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.
Internet Explorer (obsolescent should move to Firefox or Chrome)
— F12 key gets the Developer Tools, then select the console tab
Use the function console.log(message) to display the values of variables in your program as it executes. This is a useful for debugging (jargon for finding potential errors in your programs).
When loading a web page you get some
syntactic error messages, which can be more helpful than using JSLint, and
in many cases, much more convenient.
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.
The value of every variable can be both read from and written to.
Every type has 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.
Variable scope
Variables can have global and local scope
Local variable
Declared within a function, referenceable only within
the function
Global variable
Declared outside of a function,
referenceable 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.
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(separator)
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 – substr(from_index, length)
Result = "12345678".substr(2,4) gives Result = "3456" — recall that numbering
starts at 0.
Extract a substring – substring(from_index, to_index – 1)
Result = "12345678".substring(2,4) gives Result = "34" — recall that numbering
starts at 0.
Search for a particular substring — indexOf(substring)
Result is either -1 (a_string is not a substring of string) or
the index within string where the a_string begins.
var Result = "abcdefghij.indexOf("def"); gives
Result = 3 — recall that numbering
starts at 0.
Array
Arrays are one dimensional
— Have additional dimensions by storing an array as a value.
Use a list to initialize an array — theArray = ["a","b","c"]
an array can be empty — theArray = [];
Boolean
Boolean values are true and false. They arise
when making comparisons between values using the comparison operators
such as equal, greater than, etc.
Object literals
— they are also called tuples and records.
They are analogous to classes in Eiffel, and structs in C augmented
with functions.
Example: An object literal is created and written to the
web pag.
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 operator 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.
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 definitions: inner ones are hidden (private)
The prompt and confirm popup boxes
With the window.prompt("prompt message", optional_default_value)
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 false is returned, or the user can press OK, whereupon
the value true 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;
}
The recommended loop structures for the most common situations are the following.
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 (while a move is bad), 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
}
Argument list processing
example.
String comparison
example
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);
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.
=== is true only if the operand types are the same and have the same value.
== is true if the operand types are the same and have the same value but
if the types are different, then type coercion is used, which can produce
strange results. The rules for type coercion are difficult to understand
and remember.
For example in the following, one would expect the first
line to be true because the second and third lines are true. The fourth line
is plain crazy.
'' == '0' // is false
0 == '' // is true
0 == '0' // is true
' \t\t\n ' == 0 // is true
Do not use var++ and var--. Use var += 1 and
var -= 1 instead. Use of ++ and -- can lead to subtle logic errors. It
is best to use techniques that avoid the possibility of making errors.