Last updated 2017 January 14

JavaScript topics

JavaScript examples            w3schools.com for learning about Web development

Debugging

Using JSlint

You check JavaScript syntax using JSLint.

It is very strict and imposes style conventions in addition to syntax. Check the following option to remove "errors" that are not errors.

You should do the followng.

Web console

Get the web console with the following.

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.

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.

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.

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.

Datatype conversion

The w3schools conversion web page

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.
  1. if … then … else
              if (condition) {
              then phrase statements
              }
              else {
              else phrase statements
              }

    if then else example.

  2. 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;
              }

    switch example.

  3. Night out planning with nested if statements.

A loop over a block of statements

The recommended loop structures for the most common situations are the following.

  1. 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

  2. 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);

    Argument list processing example.

  3. Night out planning with while loop.

Comments

JavaScript has two types of comments.

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.
document.getElementById("ElementID").innerHTML = "NewContents";
Change an attribute value of an element
Find the element by its id, then set an attribute value.
document.getElementById("id").setAttribute("attributeName", "Value");

Error handling

Sources of errors

Error types

Catching & throwing errors

Try, catch and throw example.

Canvas

You can draw on a page with JavaScript using the Canvas element. Here are a couple of sites to help you learn about that element.

Here are some examples using the canvas element.

Regular expressions

Regular expression topics are here.

Inheritance in JavaScript

Under construction

Cookies

Not done

Bad parts of JavaScript

Why use === (!==) in place of == (!=)

=== 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.