JavaScript for beginners (third part)

first part -- second part -- third part

In previous two parts we have learned how to put a JavaScript program into web page, and what could such program do. Today we will learn how to program simple things in JavaScript. If you have never programmed before, this article can be too difficult for you; I will try to explain things simply, but programming is a complex thing, and it is not possible to explain it thoroughly in a short article. If you already have programmed in some language, you should be able to understand this. Learning to program is a bit like learning to swim -- it is not enough to stand on the beach and watch swimmers, you have to get into the water; also it is not enough to read an article on the web, you have to start a text editor, write, and try.

When programming we use data; the most frequent types of data are numbers, texts, objects, and arrays. Let's start with numbers:

<html>
 <head>
  <title>An example page with JavaScript</title>
  <script language="JavaScript"><!--

   function main() {
    var x;
    x = 10;
    alert('Variable x contains number ' + x);
    x = x + 1;
    alert('Variable x is now ' + x);
    alert('Twice x is ' + (2 * x));
    alert('Logarithm of x is ' + Math.log(x));
   }

  //--></script>
 </head>
 <body onload="main();">
 </body>
</html>

After loading web page the main function (called "main") is started. We could have called it differently, but this is a nice tradition from other programming languages. The commands in functions are executed in order, from first one to last one.

Command "var x" creates a new variable called "x"; it will exist only within the "main" function. The program would work also without this line, but if we had more functions containing more variables called "x", these variables would influence each other. Command "var x" will create a variable "x" only for this function; it will have no relation to any other variable "x" in other parts of the program. This is especially useful in longer programs, where variable names are often repeated, and the problems potentially caused by their influence could be difficult to find. Unlike some other programming languages we do not have to (and we cannot) specify what kind of data can variable "x" contain; whatever we put there, will be there.

Command "x = 10" will put number 10 into variable "x". Programmers know that the symbol "=" does not mean mathematical equality; instead it is a command to put the value 10 into the variable "x" (and forget any previous value of "x"). Therefore the later command "x = x + 1" is not an insolvable mathematical equation, but a command to put value "x + 1" (currently 10 + 1, that is 11) as a new value into the variable "x" (replacing the old value 10).

Command "alert" displays the specified text to user; in this example we use some leading texts appended by numerical value. We could have used it without the text, like "alert(x)" or "alert(2+2)", but it is nice if the user has some idea about what we are trying to tell him or her.

The basic mathematical operations are done using symbols "+" for addition, "-" for subtraction, "*" for multiplication, "/" for division. The result of division can be a decimal number; we can truncate it using method "Math.floor", for example "Math.floor(x/3)". The remainder of division can be obtained using symbol "%", for example "x%3" is a remainder of dividing "x" by three; if "x" is a natural number, the result can be 0, 1, or 2. More complex calculations can be done using functions of "Math" object, for example "Math.abs" is absolute value, "Math.sin", "Math.cos", "Math.tan" are sinus, cosinus, tangens, "Math.sqrt" is a square root, "Math.log" is natural logarithm, and "Math.exp" is exponential function.

(Programmers with knowledge of Java may have thought while reading the previous paragraph that "Math" is not an object but a class. It is not true. JavaScript is different from Java, and surface similarities can be misleading. In later lessons we will see that JavaScript uses prototypes instead of classes, and what exactly this means.)

<html>
 <head>
  <title>An example page with JavaScript</title>
  <script language="JavaScript"><!--

   function main() {
    var s;
    s = 'Bratislava';
    alert('Text length is ' + s.length);
    alert('The fifth letter is ' + s.charAt(4));
    alert('Its code is ' + s.charCodeAt(4));
    alert('Letter T is at position ' + s.indexOf('t'));
    alert('The end of text is ' + s.substr(5));
   }

  //--></script>
 </head>
 <body onload="main();">
 </body>
</html>

Texts are written in apostrophes. The letter at given position can be found using "s.charAt". We have to remember that characters in string are numbered starting at 0, so if we have a text with 10 letters, their positions are 0, 1, 2... till 9. The fifth letter is at the position 4. If we want to find a position of the letter (or part of text), we can use "indexOf" method.

If we want to select a part of text, we can use either "substr" or "substring" method. In both methods we specify the starting position (inclusive); in "substr" method the second parameter is number of characters to be selected; in "substring" method it is the ending position (exclusive). For example if we want the sixth and seventh letter, we can write "s.substr(6, 2)" or "substring(6, 8)".

Each character is assigned some number (called "code point") in Unicode standard. If we want to receive the number corresponding to a letter on given position, we can use method "charCodeAt". For example if we want to know the Unicode value of lowercase 'a' letter, it is "'a'.charCodeAt(0)". If we want to know which character has code point 97, it is "String.fromCharCode(97)".

<html>
 <head>
  <title>Calculator</title>
  <script language="JavaScript"><!--

   function division() {
    var t1 = document.getElementById("t1");
    var t2 = document.getElementById("t2");
    var t3 = document.getElementById("t3");
    var x = t1.value;
    var y = t2.value;
    var z = x / y;
    if (isFinite(z)) {
     t3.value = z;
    } else {
     t3.value = "error";
    }
   }

  //--></script>
 </head>
 <body>
  <p>
   <input type="text" id="t1" name="t1"/>
   <input type="text" id="t2" name="t2"/>
   <input type="button" value="/" onclick="division();"/>
  </p>
  <p><input type="text" id="t3" name="t3" readonly="readonly"/></p>
 </body>
</html>

Useful example -- calculator. We can write numbers into the two first text boxes; after clicking the "/" button the third text box will display the result of division. Using method "document.getElementById" we will assing text boxes on the web page into variables "t1", "t2", and "t3". Using the "value" property we can read text from the text boxes, or write a new text there.

Function "isFinite" tells if the variable "z" (with the result of the division) contains a finite number. The answer could be negative for two reasons: either some of the first two fields contains a non-numeric value, or we have divided by zero. If we divide by zero, or perform other invalid mathematical operation, we can receive return values like "infinity" or "not a number". The function "isFinite" lets us tell real numbers from such values.

Homework: Improve this calculator by adding buttons for addition, subtraction, and multiplication.

Comments: 0


Google