(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-48897844-1', 'jennifermadden.com'); ga('send', 'pageview');

Arguments

In the same way that method parameters can be assigned multiple values, arguments used in concert with a function may also be assigned multiple values when the function is invoked.

This special variable is called an argument. The argument variable is only declared, not initialized, in a function's parenthesis. It is initialized when the function is called just by including a value with the function call.

Since the same function can be called multiple times, the value assigned can be different for each call. Assigning values to argument variables in this way is known as passing arguments.

There are three steps involved in using arguments:
  1. Declare the argument in the function's parentheses.
  2. Within the function, include the argument in the location it will be used.
  3. Assign the value of the argument when the function is called.
function favoriteNumber(myArg) {// 1. declare
alert(myArg) // 2. used here
}

<input type="button" onclick="favoriteNumber('One')"> <!-- 3. assign value -->
<input type="button" onclick="favoriteNumber('Two')"> <!-- 3. assign value -->
In the above example, the value of myArg is "One" when the first call to the function is made. When the second call to the function is made, the value of myArg is "Two". If I didn't use an argument here, there would have to have been 2 functions written for each value.

Multiple Arguments

Multiple arguments can be used within the same function, just separate the arguments with commas when they are declared and when they are assigned a value.
function passStuff(myArg1,myArg2,myArg3) {
alert(myArg1 + myArg2 + myArg3)
}

<a href="javascript:passStuff('One','Two','Three')">One, Two, Three</a>
<a href="javascript:passStuff('Uno','Dos','Tres')">Uno, Dos, Tres</a>
Just for fun, try another example.
function changeBackground(myColor) {

  document.bgColor = myColor // bgColor is a property of the document object

}

<input type="button" onClick="changeBackground('green')" value="blue">
<input type="button" onClick="changeBackground('yellow')" value="yellow">
<input type="button" onClick="changeBackground('white')" value="green">

>>Functions
>>JavaScript Variables
>>Arguments
>>JavaScript Operators, Expressions and Evaluation
>>Special JavaScript Operators
>>Decision Making: If Statement, Else Clause

 


View Source | Home | Contact