Passing parameters to functions

You have already done this.  Your browser comes with the ability to run JavaScript.  The JavaScript interpreter in each browser is slightly different but all will include built-in functions.  One of those built-in functions is called alert.  So when you used this code:

alert('Hello there');

you were calling (running) the function alert and also passing some text to it.  The stuff inside the brackets is known as a parameter.  That extra text is used by alert so that it knows what to display in the message dialog box.

You can do the same with the functions you write.

Save jsfunction.html as jsparameter.html.  Open it in the browser and open the error console just in case things go wrong.  There should be no errors so far.

Look for the onmouseup event trigger in your code.  Inside the double quotes change fred(); to fred('This is a parameter'); so that the text is passed to the function when the browser runs it.

Save and try it and it should show the hello message just like before. Although we have not finished changing the code it is worth checking each change before you move on to the next one to spot errors and fix them before you add to them.  The error console would have reported them.

For the parameter to be used the function needs to receive it and store it.  At the top of the page inside the script element place a variable name inside the brackets after the function name like this:


This variable will receive and hold the parameter.  Save and try to check for errors but again not quite there.  You now need to use the variable instead of the original text so change the alert line in your code from this:

alert('Hello for one last time');

to this:


Save and try and it should work at last.  If you don't understand what is happening try looking at your code and following the sequence through from the event trigger (onmouseup) and the function being called (fred('Hello for one last time'))to the function itself (fred(theMessage)) and the alert.

Now try this to see why parameters are useful:

  1. copy the paragraph in jsparameter.html and paste it under itself so you have two identical paragraphs
  2. in the second paragraph change the text This is a parameter to So is this and you now have two messages but still one function
  3. save and try clicking on both words in turn and you should get different messages but with only one function