JavaScript - Lesson 1Learning Objectives
Creating a JavaScript programJavaScript programs are written as a series of program statements embedded in an HTML file (i.e. the instructions for a web page). HTML consists of a series of tags, and one of those tags tells it to start running a JavaScript program. This is the <script> tag as shown below: <script LANGUAGE="JavaScript"> (The JavaScript program goes here) </script> The </script> tag at the end of the program tells the web browser interpreting the file that the JavaScript program has finished and it should expect more HTML tags to follow. Whenever the program comes across a <script> tag, then it will assume that the language used is JavaScript, so the LANGUAGE="JavaScript" part of the tag isn't really necessary. The program could just as easily be written as <script> (The JavaScript program goes here) </script> However, it is generally a good idea to use the full version of the tag, in order to take account browsers yet to be introduced that may not assume that the default language is JavaScript. The HTML file containing the JavaScript program (together with any other HTML and text, of course) is saved using the file extension .htm, or .html as per normal, of course. JavaScript is an Object Oriented LanguageEverything in JavaScript takes the form of an object. This means that it is a "package", which contains various properties (pieces of information) and methods (lists of instructions that it can carry out). An example of an object in real life might be a bird. The 'properties' of the bird - the information associated with it - are its breed, its plumage colour, details of its diet etc. The 'methods' of the bird would comprise things that it knew how to do, such as sing, fly, peck, breed etc. In Object Oriented computer languages such as JavaScript, the sort of objects would be things like documents (screens), windows, variable types etc. but they still have properties and methods. The document objectHere's the first object that you will meet - document. This refers to the main screen in the browser itself, the part where the text and images appear. The document has a property (among others) called bgColor, which specifies what the background colour of the screen is (note the capital C in the middle of that. It's important. Also note that 'Color' is spelled the American way). We can use this to set the background colour of the screen. Open your text editor and create a plain text file called test1.htm containing the following text: <html> <body> <script language="JavaScript"> document.bgColor = "YELLOW"; </script> You can add some more text and/or HTML tags here, of course. </body> </html> You can add as many HTML tags to that as you like (but don't add a BGCOLOR= part to the <body> tag, of course, as we are trying to set this using JavaScript). The word document is separated from the bgColor property by a full stop (but don't insert any spaces in there!), and it is used to set the background colour to yellow. When you open the file in a browser, you should see any HTML that you have specified on top of a yellow background. N.B. The program instruction in the example above ended with a semicolon (;) Program instructions in JavaScript almost always end in a semicolon, so remember to put it in. You should also be careful about letter case. Write the program exactly as you see it here, using document rather than DOCUMENT or Document. bgColor is an example of a document property. An example of its methods is write() and you can tell that it is a method by the fact that the name of the method is followed by a pair of brackets. write() displays text on the screen. The thing that you want displayed on the screen is enclosed inside the brackets. If it is a piece of text, then remember to place it within double quotation marks: <script language="JavaScript"> document.bgColor = "YELLOW"; document.write("This should appear on a yellow background."); document.write("<p>"); document.write("This is my second JavaScript program."); </script> You will see that you can include as many document.write() instructions as you like, and that write() is again separated from the word document with a full stop. Note also the semicolon ; at the end of each program line. The second instruction writes a paragraph break on the screen (i.e. a blank line). The tag <p> in HTML causes a blank line to be inserted and enclosing the HTML tag within a document.write() statement, it has the same effect. In fact, document.write() can duplicate the effect of any HTML tag: <script language="JavaScript"> document.write("<img src=my_pic.gif />"); document.write("<hr width=40% />"); document.write("<font color=#4050ff>"); </script> You do still need to enclose the tags within quotation marks. The following would not work at all: document.write(<img src=my_pic.gif>); Another property of document is the lastModified property. This contains the date that the document was last edited - it corresponds to the file-edit date. You can't change this in the same way that you could with the bgColor property, but you can display it on the screen: document.write(document.lastModified); Again, the word lastModified should be written with all lower case letters except for the M in the middle which should be upper case. lastModified is what we call a read-only property - it can be displayed, and its value "read" by the program (for example, when testing conditions), but it can't be altered by the program. The only way of altering the lastModified property is by editing the file so that the date changes. VariablesA variable represents a piece of data stored in a computer program. All variables have a name and a value. We can think of them as being like small boxes, each of which can contain one item. The name of the variable is how we refer to the box, and the value is the item stored in the box. The diagram shows a variable called x, and the value stored in it is 14. Variables in JavaScript must be declared before they can be used. They are declared using the word var followed by the variable name and a semicolon: var age; Variable names can consist of any number of upper or lower case letters, digits and underscore characters _ but they must start with a letter. Also, variable names are case sensitive, which means that the variables names myName, MYNAME and Myname would all refer to different variables. Variables are set to values using an equals sign: age = 37; You can also display the values of variables on the screen using document.write(). In this case, put the variable inside the brackets but don't surround it with quotation marks: document.write(age); This will display the number 37. If you had put the word age in quotation marks, as follows, document.write("age"); then the word age would have been displayed on the screen. The value of variables can be changed at any point. Indeed, they can even be set to the value of other variables: <script language="JavaScript"> var x; var y; x = 26; y = -109; document.write(x); document.write("<p>"); x = 45.7; document.write(x); document.write("<p>"); x = y; document.write(x); document.write("<p>"); </script> The first number displayed on the screen is 26 (the value of x). The second number displayed is 45.7 (the updated value of x - I didn't say the numbers had to be whole numbers, did I?) and the last number displayed is -109 (after x is set to the same value as y - I didn't say the numbers had to be positive either!) All these numbers are produced by the same instruction - it's just the value of x that changes. Variables can also be set to values at the same time that they are initialised. For instance, the following two instructions var temporary_value; temporary_value = 26.09; can be rewritten in one line: var temporary_value = 26.09; You can also declare more than one variable in one line, by separating the variable names with commas (not semicolons - they only come at the end of lines). For instance, the following two lines: var a; var second; var third_variable; a = 7; third_variable = 19; second = 2400; can be rewritten as var a, second, third_variable; a = 7; third_variable = 19; second = 2400; or even as var a = 7, second = 2400, third_variable = 19; ArithmeticAs well as setting variables to different values (which isn't particularly useful on its own), we can also perform arithmetic on them. We use + for addition and - for subtraction, * for multiplication and / for division: var first = 12, second = 4; var sum = first + second; document.write(sum); document.write("<p>"); var difference = first - second; document.write(difference); document.write("<p>"); var product = first * second; document.write(product); document.write("<p>"); var quotient = first / second; document.write(quotient); document.write("<p>"); The value of sum is set to 16 (= 12 + 4), difference is set to 8 (=12 - 4), product is set to 48 (=12 * 4) and quotient is set to 3 (=12 / 4). If the division had not produced a whole number then quotient would have been set to a decimal value (so if second had been set to 5, then quotient is set to 2.4). If you want to, you can put the arithmetic entirely within the document.write() statements, although that would not set any variable values, of course. The following would produce the same four numbers as the program segment that you see above, except that the variables sum, difference etc. are not set: var first = 12, second = 4; document.write(first + second); document.write("<p>"); document.write(first - second); document.write("<p>"); document.write(first * second); document.write("<p>"); document.write(first / second); document.write("<p>"); You can also mix numbers and variable values in longer arithmetic expressions: var answer; answer = 14 + sum - product; second = 10 * quotient - answer; The value of answer is set to 14 + 16 - 48 = -18. The (new) value of second is set to 10 * 3 - (-18) = 30 + 18 = 48. Operator PrecedenceWhat value is displayed by the following? document.write(2 + 3 * 5); If you said "25", then you would be wrong. Instead of doing the arithmetic operations in the order in which it meets them (2 + 3 = 5, then 5 * 5 = 25), the multiplication is done first and then the add (3 * 5 = 15, 15 + 2 = 17) so the answer 17 is displayed on the screen. The rule is that multiplication and division are more important than addition and subtraction (we say they have a higher precedence) even if they come after the addition or subtraction. Take a look at this: document.write(40 - 5 * temp1 + 100 / temp2); In this case, the value of 5 * temp1 is calculated first, and then the value of 100 / temp2. The program then subtracts the first of these values from 40 and adds the second of the values. If temp1 had the value 7.5 and temp2 had the value 50, then the number displayed would be 40 - 5 * 7.5 + 100 / 50 = 40 - 37.5 + 2 = 4.5. As in normal mathematics, we can change the order in which the arithmetic is done by enclosing the addition or subtraction within brackets. Brackets mean "do me first", so the following new_answer = (2 + 3) * 5; really would set the value of new_answer to 25. Similarly, the following document.write((x + 2) / (x * 2 - 5)); would calculate x + 2 first, then the value of x * 2 - 5 (doing the multiplication before the subtraction) and then divide the first number by the second, displaying the answer. String variablesThe sort of variables that we have seen up to now are called numeric variables, as they have held nothing but numbers. However, we can also set variables to strings, which are words and sentences. Strings are enclosed within double quotation marks. var proverb = "Every mushroom cloud has a strontium lining."; document.write(proverb); This code segment declares a variable and sets it to the string specified. Again, no quotation marks are used in the document.write() statement as otherwise it would display the word proverb rather than the value of proverb. Variables can be re-assigned to different strings just as they can be with different numbers: proverb = "A rolling stone gathers much speed."; Indeed, variables can be assigned to a number, then to a string and then back to another number if you want: proverb = 399; proverb = "Pride comes before private in the dictionary."; proverb = -1000; That is perfectly acceptable in JavaScript, although it is not a good idea to reassign variables to strings and numbers willy-nilly. Most other programming languages forbid you from doing so, but JavaScript has what we call weak typing, and it is not fussy what values we assign to variables. You can also use the + operator with strings, or variables that have been assigned to strings. Consider the following: var name = "Richard" + "Bowles"; myVariable = "X@X#X$X"; document.write("This is a string" + myVariable + "."); The first of those instructions sets the variable name to RichardBowles and the second statement displays This is a stringX@X#X$X. This joining of one string on to the end of another is called concatenation. Note that I had forgotten to include any spaces in that, so the strings produced had no spaces. If I had wanted spaces, I should have written the statements as follows: var name = "Richard " + "Bowles"; myVariable = " X@X#X$X "; document.write("This is a string" + myVariable + "."); Mixing strings with numbersWhat happens if + is used to join a number (or numeric variable) to a string (or string variable)? In this case, JavaScript treats both of them as if they were strings and concatenates them accordingly. The following instruction sets temp_var to the string Hello123: var x = 123; var temp_var = "Hello" + 123; Similarly, the following instruction displays the string The answer is 1004: first = 1000; second = 4; answer = first + second; document.write("The answer is " + answer); However, please be careful. You might think that the following would display the string I have 8 children: document.write("I have " + 5 + 3 + " children"); However, as soon as JavaScript comes across the first +, it realises that we are using string concatenation, and it then uses string concatenation for all the other + operations in the instruction. This means that it displays 5 and 3 as their string equivalents, "5" and "3", which it joins end-to-end to produce the message I have 53 children - not quite the desired answer. If you want the 5 + 3 to be calculated as 8, then you have to insist that JavaScript does it before the other + operations, and this is achieved, as you might expect, using brackets: document.write("I have " + (5 + 3) + " children"); This does have the desired effect, and gives the message I have 8 children. The 5 + 3 is turned into 8, and then JavaScript concatenates "I have " + 8 + " children" as one large string. Here is an example where I have mixed a string with one of the document properties: document.write("Web page last changed on " + document.lastModified); | ||||||||||||
|