Start learning free

LESSON 38 OF 671 · FUNCTIONS I

Function parameters & arguments in JavaScript

Lesson

So far, the functions we've created execute a fixed task without context / inputs. But most often we want our functions to produce different outcomes depending on the context behind the function call.

For example, it would be nice if sayHello() would print a personalized message such as "Hello humans" or "Hello cats" or "Hello dogs", depending on the audience instead of "Hello world" no matter what.


Function parameters:

Function parameters allow functions to accept input(s) and perform a task using the input(s). We use parameters as placeholders for information that will be passed to the function when it is called.

When a function is defined, its parameters are specified between the parentheses that follow the function name.

Here is our function with one parameter, audience:

function sayHello(audience) {
  console.log("Hello " + audience);
}

Calling with arguments:

Then we can call sayHello() and specify the values in the parentheses that follow the function name. The values that are passed to the function when it is called are called arguments.

// Function declaration:
function sayHello(audience) {
  console.log("Hello " + audience);
}

//Function call:
sayHello("humans"); // Output: Hello humans

We have passed one string argument: "humans". Inside the function audience will equal string "humans" and acts just like a regular variable.


Multiple parameters:

A function can have as many parameters as it needs. Here is a function with two parameters:

Here is a function with two parameters:

function sayHello(name, age) {
  console.log(name + ", aged " + age);
}

// Let's call it:
sayHello("John", 30); // Output: John, aged 30
sayHello("Mary", 26); // Output: Mary, aged 26

Notice that the order in which arguments are passed and assigned follows the order that the parameters are declared.


Variables as arguments:

Variables can also be passed as arguments for function calls:

function sayHello(name, age) {
  console.log(name + ", aged " + age);
}

let name = "Andy";
let age = 28;

sayHello(name, age); // Output: Andy, aged 28

sayHello("Mary", age); // Output: Mary, aged 28

Assignment
Follow the Coding Tutorial and let's write some functions.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 5
    Ctrl + Enter to check