javascript
Brief description  about Online courses   join in Online courses
OR

Javascript Function

Shatish  Rao
Shatish Rao
Project Lead - Java

Functions are simply sectioned-off pieces of code. When you want to use your code segment, call it by its name and it will come running.

Passing  value to a function

So far with functions, we have just been doing this sort of thing:

function add() {
Our code segment here
}

The name of the function is add. Immediately following the name are a pair of round brackets ( ). To call (use) our functions, we've doing this:

<Input Type = button onClick = add()>

Inside the round brackets, we haven't put anything. They have been empty brackets. But functions are given extra power by putting something inside the brackets. This "something" is called an argument. An argument is really just a variable. What you're doing by giving your function an argument is passing a value to your function.

Our first function will accept one argument. The value being passed to our function comes from the number buttons on our calculator. If you have a look at the HTML calculator code in the page you saved, you'll see this for the buttons:

<Input type = button name = b1 value = " 3 " onClick =calculate(3)>

The value above is the text on the button face. This is the number three button. When this is clicked, the number three will appear in the display. Look at the onClick event:

onClick =calculate(3)

The onClick event is calling our function, which has the name calculate().

function calculate(number) {

}

Our function now accepts an argument - number. This is a variable into which we can place values. When the 3 button is clicked on the calculator, a value of 3 will be placed into the number variable. If another button is clicked, the 7 button for example, a value of 7 will be passed to the number variable. We can then use this number variable in our code for the function:

function calculate(number) {
frm = document.frmOne.txtDisplay
frm.value = frm.value + number
}

You should be able to work out what the code for the function does, but here's an explanation. The Display textbox is first put into a variable called frm. We then add whatever is in the variable number (our argument) to whatever is already in the display text box. Here, add means "join together". So if you wanted 22 in the Display text box you would click the 2 button twice.

This is a nice, simple function that display numbers in a text box. You can add the function to your calculator. Either type or copy and paste the function into the HEAD section of your code.

OK, now that we know how to pass a value to a function, we can set up a second function to deal with the operators. When you click one of the operator buttons (plus, minus, etc) you can pass the operator to a new function in the same way you've just done. First, set up the onClick event in the HTML form (this has already been done):

<Input Type = Button value = " plus " onClick = operator("+")>

Notice the name of our new function, and the value we are going to pass to it when the "plus" button is clicked:

onClick = operator("+")

What we're passing to our new function is the plus symbol ( + ). We're passing it as a string, hence the double quotes surrounding it. For the divide button, we have this for the onClick event:

onClick = operator("/")

In other words, a different symbol will be passed to our new function depending on which operator button is clicked. Here's the code for the function:

function operator(opval) {
TheOperator = opval
total = document.frmOne.txtDisplay.value
document.frmOne.txtDisplay.value = ""
}

This time, the variable inside our function is called opval. This is our argument. When an operator button is clicked, opval will contain one of our four symbols. Inside the function we then pass this value to a variable which we have called TheOperator. Besides passing the operator symbol to a variable, this function also gets the value from the display and passes it to a variable called total. The text box is then cleared ready for another number to be entered.

So add this new function to your script, just below the first one. However, the variables total and TheOperator need to have their values read from another function. So we have to make them global. We do this by declaring them at the top of the code, just before the first function:

<SCRIPT Language = JavaScript>

var total = 0
var TheOperator = 0

function calculate(number) {
frm = document.frmOne.txtDisplay
frm.value = frm.value + number
}

function operator(opval) {
TheOperator = opval
total = document.frmOne.txtDisplay.value
document.frmOne.txtDisplay.value = ""
}

</SCRIPT>

With our two global variables set up, we can now do the calculating part. The calculating is done when the equals sign is clicked on the calculator. Again, we do this with an onClick event. This time from the equals button on the form:

<Input Type = Button value = " = " onClick = equals()>

We don't need to pass anything to our equals function (it's a simple little code segment), so we're back to the empty round brackets. This means that it's a function that doesn't accept arguments. Here's the entire function that does the calculating:

function equals() {

CurentDisplayValue = eval(document.frmOne.txtDisplay.value)
PreviousDisplayValue = eval(total)

if(TheOperator =="+") {
answer = PreviousDisplayValue + CurentDisplayValue
}
else if(TheOperator == "*") {
answer = PreviousDisplayValue * CurentDisplayValue
}
else if(TheOperator == "-") {
answer = PreviousDisplayValue - CurentDisplayValue
}
else if(TheOperator == "/") {
answer = PreviousDisplayValue / CurentDisplayValue
}
document.frmOne.txtDisplay.value = answer
}

The code looks a tad messy, but that because of the variable names we've chosen to use. First, we pass whatever is currently in the Display text box to a variable called CurentDisplaValue:

CurentDisplayValue = eval(document.frmOne.txtDisplay.value)

The eval() part just ensures that JavaScript doesn't try to concatenate when we want to add up. The second line of our code gets the value stored in our global variable total and passes it to the new variable called PreviousDisplayValue:

PreviousDisplayValue = eval(total)

The rest of the code just uses if statements to check what is inside our other global variable TheOperator. The final line just pops the answer into the Display text box.

And that's it. A very simple calculator that demonstrates how to pass values to functions by setting up arguments. You can pass more than one argument at a time to a function. But we've kept things simple by using only one argument with each function.
Add the new code to your calculator and see it in action.


Calling other functions within a function

Functions can call other functions, and have a value passed back to the calling line. We'll see how that works now. Once you have grasped the concept, what we're then going to do is write code to validate data that a user might enter on a form.

First, though, here's an example of a function being called inside another function. To test it out, create a web page with a button on it. Set the onClick event for the button to this:

onClick = GetValue()

Once you have your web page with a button on it, add this code to the HEAD section of the page:

<Script language = JavaScript>

function GetValue() {

return value()
}

function returnvalue() {

n1 = 10
n2 = 5
answer = n1 - n2
return false
}

</SCRIPT>

When the button on your page is clicked, it calls the function GetValue(). The only line of code in the GetValue() function calls the second function:

returnvalue()

When this second function is called, all the code inside it is executed. Control then passes back to the first function. Any other lines for the first function are then executed.

Notice the line of code that reads return false. We really should have had this return word at the end of all our functions. It's actually a question: "Does the function return a value?" In other words, Are we finished with this function or not?

If the function does return a value you can either use return true, or more likely you can return a value back to the first function. In our second function, we were subtracting one number from another and putting the answer into a variable called answer. But we weren't doing anything with this variable, so nobody would be able to see what the answer was. In this next example, we'll return the answer to the first function:

function GetValue() {

total = returnvalue()
alert(total)
}

function returnvalue() {

n1 = 10
n2 = 5
answer = n1 - n2
return answer
}

The first function now does something slightly different. The call to the second function, returnvalue(), has gone on the right hand side of an equals sign (= ). On the left hand side of the equals sign we have a variable called total. What we're saying here is "Assign the value of returnvalue() to the total variable."

But the same thing happens: the second function is called and has its code executed. However, we've now told the second function to return a value:

return answer

And what's inside the answer variable? The answer to the sum 10 - 5. This is the value that gets passed back to the calling line, which was:

total = returnvalue()

Now the variable total will hold the value from the function. Finally, we've displayed the result in an alert box. Run the code and see how it works

Write your comment now