{{{{ JavaScript - Functions and Variables }}}}

Functions
When code is actioned
Comments
Variables
Global and local variables
Function with parameter
Random number generator (function returning value)
Start of website

Alphabetical index

Summary of colours in code: green is HTML useful for JavaScript, red is JavaScript, blue is a name and everything else is grey.



Functions

All of the input and output examples that we have seen so far have used JavaScript in the <BODY> of the HTML code, usually as part of ONCLICK or ONKEYUP or something similar. In some cases this leads to rather cumbersome code. In fact, usually JavaScript is put inside the <HEAD> of a webpage, which separates the code from the formatting of the webpage (which stays inside the <BODY>). This makes it easier to see what is going on, and so easier to get the code working. You do this by using function.

In the example below, there are two text boxes. You type a number in one and the square of the number appears in the other. However, ONKEYUP of the input box does not contain the calculation, it says "sqnum()" instead. This is a JavaScript function. I have defined the JavaScript function inside the webpage <HEAD>. Since this is JavaScript, and is not inside an ONKEYUP or similar, I have to surround the code with <SCRIPT TYPE="TEXT/JAVASCRIPT"> --- </SCRIPT> (if you forget this, it will treat the JavaScript as HTML!)

The function has the name "sqnum()". You can use any name that is not used already by JavaScript, or anything else in your webpage (so I couldn't use "square", as I'd used it already as a FORM name). Click here for a list of words that you should not use as a data name, as they already specifically have a meaning in JavaScript or HTML. I define the function like this: function sqnum() {---} where --- is the code that I want the function to do. The code could be several lines of JavaScript code, if I wish, but in this case it's just one line. Look at that definition carefully - all the funny characters have to be included. You say function, followed by round open bracket, followed by round close bracket, followed by curly open bracket, followed by the code, followed by curly close bracket. You do need all those brackets, and they must be of that type - JavaScript is very fussy about this! When you call the function, the name must be followed by round open bracket, round close bracket. If you miss them out, or if you forget one or other of them, your webpage will not work. You will see that the definition of the function doesn't have to be on one line. In fact, I always type my functions the same way, with the first line including the open curly bracket, and the close curly bracket on a line all by itself. This helps me check that I haven't forgotten it! I also type all the brackets to begin with, then use the back arrow to put the code in. That way, I always type the open/close bracket as a pair, and don't forget the close bracket. Well, not too often, anyway!

Enter Number

Square
<HTML>
<HEAD>
<SCRIPT TYPE="TEXT/JAVASCRIPT">
function sqnum() {
document.square.out.value = document.square.inp.value * document.square.inp.value
}
</SCRIPT>

</HEAD>
<BODY>
<FORM ACTION="#" NAME="square">
Enter Number
<INPUT TYPE=TEXT NAME="inp" SIZE=6 ONKEYUP="sqnum()">
<BR><BR>Square
<INPUT TYPE=TEXT NAME="out" SIZE=6 DISABLED>
</FORM>

</BODY>
</HTML>

JavaScript tends to like curly brackets. That's why I use them in my headings! They are situated near the top right of the letter keyboard, and you need a shift.



When code is actioned

It is important to understand which piece of code gets actioned when. Defining a function, as I do inside the <HEAD> above, does not cause the code to be actioned. Functions just sit there, ready for you when you want it. If I hadn't mentioned the function name somewhere in the <BODY> of the webpage (which I do, inside the ONKEYUP) then it would never do it at all.

There are three places to put JavaScript code: ONKEYUP doesn't need <SCRIPT> round it as it knows it's JavaScript, but the other two do need <SCRIPT>. We have already seen an example of JavaScript inside the <BODY> of a webpage when we set the cursor to appear in a textbox.

This example doesn't do anything particularly useful, but I hope it demonstrates what happens when. The code seems to set the value of the output box to "A", "B", "C", or "D". The start value is "D", and this is because the JavaScript code is in the <BODY> on the webpage by itself (that is, not dependent on a button or anything) so the box gets set to that when the webpage is loaded. You could, of course, have had a call to a function here instead. If you click Button B, you get a "B", and this is done by JavaScript code inside the ONCLICK. If you click button A, it calls the function "seta()", which means you get "A". You never get "C" at all! Although "setc()" is defined, it is never called, so never happens.

<HTML>
<HEAD>
<SCRIPT TYPE="TEXT/JAVASCRIPT">
function seta() {
document.let.out.value = "A"
}
function setc() {
document.let.out.value = "C"
}
</SCRIPT>

</HEAD>
<BODY>
<FORM ACTION="#" NAME="let">
<INPUT TYPE=BUTTON VALUE="Button A" ONCLICK="seta()">
<INPUT TYPE=BUTTON VALUE="Button B" ONCLICK="document.let.out.value = 'B'">
<INPUT TYPE=TEXT NAME="out" SIZE=1 DISABLED>
</FORM>

<SCRIPT TYPE="TEXT/JAVASCRIPT">
document.let.out.value = "D"
</SCRIPT>

</BODY>
</HTML>




Comments

Comments are stuff you put into code which gets ignored by the computer. If you are not a programmer, you may ask "Why on Earth...?" (And if you are a programmer, you're probably muttering to yourself that you don't need comments. Oh yes, you do!)

The main point of comments is to write yourself (or anyone else who might read the code) a short note to say what this piece of code actually does. If you define a function for example, it would be a good idea to mention what the function does, especially if you have given it a silly name like "fred". A short comment, such as "changes colour of mosaic tile" or "clears mosaic" makes all the difference to finding where you are in the code.

In JavaScript, if you type // then the rest of the line will be ignored. This means that if you type // at the start of a line, the whole line will be ignored. So it's quite a good idea to start every function with a comment like this:

// Sets the output box to A

function seta() {
  document.let.out.value = "A"
}

A blank line stops the comment from getting mixed up with the code. It also makes a break between the different functions, which helps you find what you want easier. You may notice that I have put a couple of spaces before the actual code of the function to make the code easier to read. Javascript is fairly relaxed about spacing and formatting. Spaces inside a literal (inside quotes) will matter and you should not have an end-of-line inside a literal. Generally speaking you start a new JavaScript statement on a new line. If you want to put more than one statment on a line, (for example, if they are short and connected to each other), then you need to put a semi-colon, ; between them. But apart from that, space out and format the lines to make them easy to read.

You may want to have much longer comments, and couldn't be bothered to type // at the start of every line. If you type /* then JavaScript will ignore everything until it meets */ so you can type /* at the start of a block of comments and */ at the end.

// and /* -- */ only work in JavaScript. If you want comments in HTML, there is no equivalent to //, since HTML doesn't really believe in lines of code. Instead, type <!-- at the start of the comment and --> at the end.

There is another way that you can use comments, and that is to actually debug your code (get the mistakes or 'bugs' out of it). Quite often, you can't find where the actual bug is. The code won't do what you want and you don't know where the problem is. One thing you can do is to work out roughly which chunk of code you suspect the bug to be, and comment it out (make that chunk into a comment by putting /* and */ at start and finish). Run the page again and see if you still have the problem. If so, comment out a larger chunk, or possibly a different chunk. When you have 'trapped' the bug within a chunk of code, gradually change the comments to enclose a smaller and smaller piece of code. I have narrowed it down to a single statement sometimes before I found the mistake! There are other tips for debugging in Programming Tips.

In these examples, I am going to make the comments grey, as they don't really fit into any of the other colour categories.



Variables

Computer programs do things to stuff. This stuff is called data. Data can be input by the user of the program, or it can be generated by the program itself. However, inside the program, you need to refer to the data, and you do this with variables.

We have met variables already. When you use a text box, you need some way to refer to the contents of the text box, whether input or output. You say "document.formname.inputname.value". Now, strictly speaking this isn't a variable. In JavaScript, there are objects and properties and methods and all sorts, but I've never quite understood them! What I will give you in this website is code that works, rather than an explanation of how JavaScript works. As far as I'm concerned, document.formname.inputname.value behaves like a variable, so that's what it is. It looks complicated because it is linking HTML to JavaScript, so the JavaScript needs to know which FORM and which INPUT within that form you're talking about, and that you're talking about its value rather than anything else about it. (The "document" is referring to the webpage itself. Since we're staying within one webpage, it seems silly to have to keep saying so, but you have to, to make the code work).

You will be glad to know that variables within JavaScript are much easier. You make up a name, like you have already for NAME= in INPUT statements. It's very important that you don't use a variable name the same as anything in JavaScript or HTML. Make it a sensible name, and not too long (in case you start mis-spelling it!). When you have defined your variable, you can make it equal to something else, or to a calculation. In the example below, I have rewritten the code for the temperature convertor to use a function and variables (although I haven't bothered to set the cursor in the text box). The HTML becomes a lot simpler, since the ONKEYUP merely refers to the function "convert()". All the code is in the function. First, I set a variable "intemp" to the input temperature. This means that I don't have to keep using that long phrase. I could if I wanted to, but it would make the code cumbersome. Then I calculate the output temperature, and this time, I break it down into several steps. It's up to you whether you prefer to make the calculation in one go, or whether you break it up like this. Note that "outtemp" happens on both the left and right of the calculation. The "=" doesn't mean that the two sides are equal (obviously - since outtemp can't be equal to five times outtemp!) It means do the sum on the right using the original value of outtemp, then put the answer in outtemp (which will overwrite the original value).

This code is longer than the original, but it is broken down into simple lines, which are easier to understand (and easier to find mistakes in!) Once you start writing long programs, you will have to use functions and variables.

Enter Fahrenheit

Celsius
<HTML>
<HEAD>
<SCRIPT TYPE="TEXT/JAVASCRIPT">

// Converts Fahrenheit to Celsius

function convert() {
  intemp = document.temp.fahr.value
  outtemp = (intemp - 32)
  outtemp = outtemp * 5
  outtemp = outtemp / 9
  document.temp.cels.value = outtemp
}
</SCRIPT>

</HEAD>
<BODY>
<FORM ACTION="#" NAME="temp">
Enter Fahrenheit
<INPUT TYPE=TEXT NAME="fahr" SIZE=3 ONKEYUP="convert()">
<BR><BR>
<INPUT TYPE=TEXT NAME="cels" SIZE=3 DISABLED>
Celsius
</FORM>
</BODY>
</HTML>




Global and local variables

In the previous example, we have defined the variables (told the computer that they exist and what their names are) by setting them equal to something else. You can certainly do it this way, but you can also define them explicitly, as below. var sets up a variable for you, and it's a good idea to set it equal to something so you know what it has in it! This example defines two variables in two different places. "loc" is defined inside the function, just before you use it. This makes it a local variable. Every time you call the function (which in this example you do by clicking a button), it will define the variable again, forgetting any previous use of the variable. Often this doesn't matter. In the previous example, the variable was just a temporary working space, and we didn't need to remember any values from one call of the function to the next. However, here, we are trying to give powers of two (1, 2, 4, 8, 16, 32, etc.) Every time you click the button "loc" gets defined again, and set back to 1, so it keeps giving 1 * 2, or 2, which isn't what we want! We need a global variable. This is defined at the top of the JavaScript, outside any function. In fact, it's quite a good idea to regularly have a variable definition area at the top of your code before you start writing the program, as then you can slot in definitions of variables as you need them. "glob" is defined only once, when the page is loaded, and it is then set to 1. So every time you click the button, "glob" still has its value from last time, and so doubles up nicely.

It is a good idea to make every variable a global one unless you really are just using it for temporary work space. It is surprising how often you think a variable can be local, and then you find yourself calling another function (which you can do from within a function, just as you can from within ONCLICK, etc.) which also uses the variable, and the new function can't find it! What then happens is that the new function will define another local variable with the same name, and you're left wondering why your data has disappeared.


Global variable
Local variable
<HTML>
<HEAD>
<SCRIPT TYPE="TEXT/JAVASCRIPT">

// Definitions

var glob = 1

// Double (powers of 2)

function doub() {
  var loc = 1
  glob = glob * 2
  document.out.global.value = glob
  loc = loc * 2
  document.out.local.value = loc
}
</SCRIPT>

</HEAD>
<BODY>
<FORM ACTION="#" NAME="out">
<INPUT TYPE=BUTTON VALUE=""Click more than once"" ONCLICK="doub()">
<BR>Global variable
<INPUT TYPE=TEXT NAME="global" SIZE=8 DISABLED>
<BR>Local variable
<INPUT TYPE=TEXT NAME="local" SIZE=8 DISABLED>
</FORM>
</BODY>
</HTML>




Function with parameter

When learning about functions, we saw that the function name has to be followed by "()" (open and closed round brackets). You may have wondered why. The reason is that functions can have parameters, and these go inside the brackets. Even if your function doesn't have a parameter, you still need the brackets to show that it doesn't have a parameter! So what is a parameter?

Quite often in programming, you have several lines of code which you want to do in more than one place. The obvious thing is to make it into a function, and call the function in more than one place. However, you may not want to do exactly the same thing each time. In this example, when you click on a radio button, a letter gets added to the end of the string. I have to define the string as a global variable since it is being used all the time. I could define 4 functions, one for each letter. However, I have one function, and the letter to be added is a parameter "let", which is inside the round brackets. When I call the function, there is the letter inside the brackets. In fact, I call it four times, each time with a different letter. This means that "let" is set equal to that letter, and then the function is run with that value in "let". You can call a function with a variable as a parameter rather than a string, like here. You can also have more than one parameter - they have commas between them - but you must have the same number of parameters in the definition, in the function command, as in the function call.

You may find this rather a silly program, and I'd agree with you! The example page has the whole alphabet, which is slightly better, but wouldn't it be quicker just to type the letters in directly?

Eagle-eyed readers may notice that sometimes the NAME in INPUT statements has quotes round and sometimes it doesn't - you can get away without. You can also leave out the quotes round RADIO, and in fact have RADIO as upper or lower case. There is quite a lot of flexibility in this, since it is HTML. JavaScript is a lot more fussy - I've just had great problems finding a bug in one of these programs because I'd typed var with a capital V, and JavaScript didn't like it!

Clear
A
B
C
D
<HTML>
<HEAD>
<SCRIPT TYPE="TEXT/JAVASCRIPT">

// Definitions

var str = ""

// Add a letter to string

function add(let) {
  str = str + let
  document.build.st.value = str
}

// Clear string

function cl() {
  str = ""
  document.build.st.value = str
}
</SCRIPT>

</HEAD>
<BODY>
<FORM ACTION="#" NAME="build">
Clear
<INPUT TYPE=RADIO NAME=choose ONCLICK="add('A')">A<BR>
<INPUT TYPE=RADIO NAME=choose ONCLICK="add('B')">B<BR>
<INPUT TYPE=RADIO NAME=choose ONCLICK="add('C')">C<BR>
<INPUT TYPE=RADIO NAME=choose ONCLICK="add('D')">D<BR>
<INPUT TYPE=TEXT NAME="st" SIZE=40 DISABLED>
</FORM>
</BODY>
</HTML>




Random number generator (function returning value)

So far, functions have either been simple chunks of code, or code driven by one or more parameters. But you can make a function return a value. That means when you call it, it makes a value, and you can set something equal to this, almost as if the function was variable. It's not really a variable, of course. It can hand over a value to something else, but not receive a value from something, that is, it can appear on the right of an equals sign but not the left. The example below is a random number generator. You can hand it a maximum number, and it will give you random integers (whole numbers) from one to the maximum. The HTML allows you to change the maximum (the start value is ten), and click on the button for as many random numbers as you want.

The random numbers are generated by the function "rnd". The JavaScript Math.random() gives you a random decimal between 0 and 1, which isn't what we want. I multiply that by the maximum, and then make it into the next integer up (which is what the JavaScript Math.ceil() does). It doesn't matter if you don't understand this, just accept that "rndnum" ends up with the random number that we want. There is a longer description of this in Mathematical Functions. Then we have the JavaScript return rndnum. This means that if anyone calls "rnd()", they will get whatever is in rndnum. Further down, this is what I do. I set the output text box value equal to "rnd()" with a parameter of the input text box value.

Enter maximum



Random number
<HTML>
<HEAD>
<SCRIPT TYPE="TEXT/JAVASCRIPT">

// Random number generator

function rnd(max) {
  var rndnum = max * Math.random()
  rndnum = Math.ceil (rndnum)
  return rndnum
}

// Call random number generator

function outrnd() {
  document.testrnd.rand.value = rnd(document.testrnd.maxrnd.value)
}
</SCRIPT>

</HEAD>
<BODY>
<FORM ACTION="#" NAME=testrnd>
Enter maximum
<INPUT TYPE=TEXT NAME="maxrnd" VALUE=10 SIZE=5>
<BR><BR>
<INPUT TYPE=BUTTON VALUE="Generate random number" ONCLICK="outrnd()">
<BR><BR>Random number
<INPUT TYPE=TEXT NAME="rand" SIZE=3 DISABLED>
</FORM>
</BODY>
</HTML>

If you want a random number in your webpage, then copy the function "rnd(max)" into your JavaScript. You can then say something like "randomnum = rnd(25)" if you want a random number between 1 and 25. Random numbers are very useful for making programs more interesting. It means that your program doesn't do the same thing every time!

A return by itself, without any variable, can be used to exit a function in the middle. This only makes sense if you are using an if statement.





Return to JavaScript index



Valid HTML 4.01!

© Jo Edkins 2005