Skip to main content

Passing Parameters to Functions

One of the reasons to use functions is to gain control over when some chunk of JavaScript code gets executed. It's easy to use functions to set things up so that code doesn't run until the user clicks a form button. Another major reason to use functions is to avoid repeating code unnecessarily. Consider the two functions.

function make_background_red() { 
    document.bgColor = "red"
function make_background_white() { 
    document.bgColor = "white"

These functions perform the same task-changing the background color-and the only difference between them is one changes the color to red and the other changes it to white. Whenever you end up with two or more functions that do essentially the same thing, then you know that your code is inefficient.

So how do you make the code more efficient? That's where the arguments come into play. An argument is a value that is "sent"-or passed, in programming terms-to the function. The argument acts just like a variable, and it automatically stores whatever value is sent.

As an example, you can take the previous two functions, reduce them to a single function, and set up the color value as an argument. Here's a new function that does just that:

function change_background_color(new_color) { 
    document.bgColor = new_color

Next: SAQ2