///Learning to Function and Loop

Learning to Function and Loop

Learning to Function and Loop

HTML is boringly static, it’s rigid, and, is least interactive. DHTML makes it dynamic and responsive. Now, DHTML is not another of those nerdy technologies, it’s just that when we come up with a concoction of HTML + JavaScript (or VBScript), the guys call it DHTML just to sound cool. DHTML stands for, Dynamic Hyper Text Markup Language (ok, so now you can actually figure out what’s all with HTML).

In the last section we explored the holy terrain of JavaScript variables. We learnt what all can be achieved by JavaScript variables, how to declare them, how to store values in them, and how to perform basic calculation with them and feel good about ourselves later on. From now onwards, we’ll be actually writing programs that solve real-world problems, and hence, it makes sense to get on friendly terms with them.

We start with loops straightaway, as the purpose of these online articles is to give you a head start, and leave the trivialities to your individual intellectual pursuits. We start with a logical program that uses looping logic. Here it is:

<script language="JavaScript">

function addthem(n1, n2)
{
n1=n1*1;
n2=n2*1;
return n1+n2;
}

var keepsum=0;
var n=0;

do{
n=prompt("Enter a number, zero to stop.");
keepsum=addthem(keepsum, n);
document.write(n + " " + "<br>");
}while(n!=0)

document.write("—————" + "<br>");
document.write(keepsum + "<br>");
document.write("—————");

</script>

Note: After a curly bracket, and after a while statement, we don’t need to put a semi-colon.

This is a multi-purpose script, and there is a profound reason behind it. Not that it’s a complete application in itself – I call it multi-purpose because it enables us to learn many things in one go. It foremost, along with the loopy business, teaches us how to use functions. Up there we could have done without the addthem() function because the things being done there are only done once, and hence leaves its application redundant. It’s just here for educational practicality.

We can declare a function like:

function(parameter1, parameter2, …, parametern)
{
do this;
do that
}

If you want the function to return a processed value, then you have to send to it a few parameters. It’s like, if you want to use a grinder in your kitchen, you have to put in something to grind (be careful with your hand).

The addthem() function accepts two parameters, namely keepsum and n, and then returns their total to be stored as a new value in keepsum. As you can see, a function in itself is a tiny program. JavaScript is full of functions. Since JavaScript is basically Object Oriented, instead of functions, we call them methods. For instance, in document.write(), write() is a method that sends text to the HTML page.

We have used (this "we" business is getting on my nerves, next time I’ll use I) do{…}while() loop in the above script. This sort of loop ensures the execution of the statements within the curly brackets at least once. A typical loop keeps executing a set of statements until the condition that makes it loop, is set to false. For example, I’ll keep on eating until my stomach is full.

Primarily, there are three loops, viz., do{…}while(), while(){…} and for(){…}. The first one we have applied above. It accepts a value, adds that value to keepsum, and then sends that value to be printed on our HTML page, until the user enters zero. Once zero is entered, the program comes out of the loop, and stores the sum of all the values entered during the loop. Isn’t it clever?

do{…}while(n!=0) ensures that loop is executed at least once, because it checks for the value of n after executing the statements. Had we used while(n!=0){…}, then the program would have first checked the value of n, and had it found the value to be zero at the first case itself, the loop would have never run.

Learning Javascript Loops

In the previous page, one thing might have baffled your sensitive nerves, and I apologize for being negligent. In the addthem() function, there were two lines of code:

n1=n1*1;
n2=n2*1;

Why the hell did I do that (not the sinful omission, but n1=n1*1)? Well, JavaScript has some sentimental hang-up while adding up two variables. They get added in a string sense. That is, if the above arm-twisting is not exercised, n1+n2 results in n1n2 and not the sum, that is, n1(=2) + n2(=5) gives 25 and not 7. So I consulted with a few King Solomon type developer friends of mine and we came up with this method. When we multiply a variable with a number, the answer is generally a number.

Now the weight is off my conscience. And we move ahead to other incarnations of loops. We have covered do{…}while() and as far as I know, we are content with the explanation. See the example of a while(){…} loop below:

<script language="JavaScript1.2">

function addthem(n1, n2)
{
n1=n1*1;
n2=n2*1;
return n1+n2;
}

var keepsum=0;
var n=0;

while(n!=0){
n=prompt("Enter a number, zero to stop.");
keepsum=addthem(keepsum, n);
document.write(n + " " + "<br>");
}

document.write("—————" + "<br>");
document.write(keepsum + "<br>");
document.write("—————");

</script>

It’s the same old program, I imagine you mumbling. The only change I have done here is, instead of using the do{…}while() loop, I have incorporated the while(){…} loop, which first checks the value of n. Since n has already been initialized to zero, the loop refuses to execute, and we are dumped on the first line just after the loop. Change the value of n to anything other than zero, and the loop has no qualms. Very fussy, huh? Well, that’s the hidden beauty of a loop, or in fact, a program – a program is strictly conditional, it has no concept of unconditional love.

The above two progressions, if you were able to assimilate, were of the infinite type. Unless you enter zero, the loop goes on and on. It doesn’t depend on a finite number, although we can conveniently use both the above loops for a finite number of times, for instance:

var n=0;
do{
document.write(n + "<br>");
n++;
}while(n<10)

It prints ten numbers from 0-9. The same can be achieved in the following, elegant manner:

for(var n=0;n<10;n++)
document.write(n + "<br>");

See how considerably it has reduced the number of programming lines? This is the most preferred loop in such a case. We haven’t used the curly brackets because there is only one statement associated with the for() loop, and hence, the semi-colon.

Very quickly now, we implement a small function into an HTML page. Create a new HTML page, or open an old one. Just above the <body> </body> tag, insert the following JavaScript:

<script language="JavaScript1.2">

function dispmess()
{
var messtoshow="Welcome to my page. ";
messtoshow=messtoshow + "The title of this page is: ";
messtoshow=messtoshow + document.title;
alert(messtoshow);
}

</script>

and modify the tag in such a way:

<body onload="dispmess();">

Save the page and see what happens.

We have assigned a JavaScript function to the OnLoad attribute of the <body> </body> tag. It tells the HTML browser to run the script as soon as the page is loaded, and this is how we assign various JavaScript functions to various HTML events. In the next section, we see how this quality helps us process the data entered in a form by a visitor. Cool?

2010-05-26T10:59:02+00:00 June 1st, 2005|JavaScript|0 Comments

About the Author:

Amrit Hallan is a freelance web developer. You can checkout his website at http://www.bytesworth.com. For more such articles join BYTESWORTH REACHOUT at http://www.bytesworth.com/br/default.asp or if you have a web dev related question then post it at http://www.business180.com/index.php

Leave A Comment