1.

Solve : Javascript function help?

Answer»

So I am doing this tutorial on w3schools, and this is the code:
Code: [Select]<html>
<head>
<script type="text/javascript">
function product(a,b)
{
return a*b;
}
</script>
</head>

<body>
<script type="text/javascript">
document.write(product(4,3));
</script>

<p>The script in the body section calls a function with two parameters (4 and 3).</p>
<p>The function will return the product of these two parameters.</p>
</body>
</html>


What I don't understand is in this line;
Code: [Select]function product(a,b)
Why do the variables have to be in the parameters, when the operation is being declared here;
Code: [Select]return a*b;
And the values of the variables are declared here:
Code: [Select]document.write(product(4,3));
LIKE, why are the variables there twice? I mean does it really need to be? Is the first one just declaring the values, and then the code in the body is giving them their values?

the function line is a declaration.

a,b are defined as parameters.

if they were, for example, ValA and ValB, they would be referred to as such in the function body. otherwise how would the interpreter know that a*b were the parameters passed rather then new variables being defined?


The values of the variables are not "declared". what you refer to is the function call. the function can be called repeatedly with different parameters, and the parameters passed and their values are used within the function through the parameter names.
Okay so the variables have to be declared before you can use them in an operation like that?Quote from: GOOGLE on NOVEMBER 22, 2009, 08:47:29 AM

Okay so the variables have to be declared before you can use them in an operation like that?

No- your missing what I mean.

If you had something like this:

Code: [Select]var a, b;
a=34;
b=12;
c=a*b;

the "var" line is unneeded; it will work either way. However, if you have a function like that you described above, but WITHOUT parameters:

Code: [Select]function product()
{
return a*b;
}

then it would be necessary to assign values to a and b before CALLING the function.
Code: [Select]a=13;
b=5;
c=product();

the "definitions" as you call them, in the parameter list of the function, tell the calling procedure how many arguments can be passed AND also tells the interpreter what they are to be referred to as in the function body.


Discussion

No Comment Found