Skip to content

Try our new Crash Courses!

Buy one of our new Crash Courses, now hosted on Teachable.

Function with parameters – JavaScript

Summary

Function with parameters:

function myFunction(param1, param2) {
  // Insert code here
}

// Call function
myFunction(arg1, arg2);

Details

A function allows you to group one or more lines of code together and give the group of code a name. You can then reuse this group of code whenever you need to by writing the function name (with parentheses).

Parameters

A function name always has parentheses at the end, both when it’s being defined and when it’s being called. To make the function more dynamic, you can add parameters. Parameters allow you to pass in data to the function. You can then manipulate that data inside of the function.

Note: the term(s) inside the parentheses when you call the function are called arguments (you can think of parameters as the placeholders and arguments as the real data you pass in to the function).

Here’s what a function with one parameter would look like:

function myFunction(param1) {
  // Insert code here
}

// Call function
myFunction(arg1);

Here’s what a function with multiple parameters would look like. Notice that the parameters and arguments are separated using commas.

function myFunction(param1, param2) {
  // Insert code here
}

// Call function
myFunction(arg1, arg2);

You can use other operations or functions inside the function to work with the parameters. Here’s an example of a function with parameters that adds them together and prints out the answer to the console:

function addNumbers(num1, num2) {
  const answer = num1 + num2;
  console.log(answer);
}

// Call function
addNumbers(2, 3); // This will print out 5 to the console

Demo

Exercises

Try the following statements in the console:

function addNumbers(num1, num2) {
  const answer = num1 + num2;
  console.log(answer);
}

addNumbers(2, 3);

The output should be 5.

References

function declaration on MDN

Back to: JavaScript Reference > JS Functions