Parameters and Arguments

Grade 6, page 3 of 11. A two-minute read.

Our banner always says "Welcome, friend!" That's a bit impersonal. What if we want to welcome people by name? We need a way to pass information into the function.

That's what parameters are for:

JavaScript
function greet(name) {
  console.log(`Hello, ${name}! Great to see you. 👋`);
}

greet("Mia");
greet("Omar");
greet("Professor Semicolon");

It prints

Hello, Mia! Great to see you. 👋
Hello, Omar! Great to see you. 👋
Hello, Professor Semicolon! Great to see you. 👋

The name in function greet(name) is a parameter. It's like a variable that only exists inside the function, and it gets its value from whatever you put in the parentheses when you call the function.

When we call greet("Mia"), the value "Mia" is called an argument. JavaScript takes the argument and puts it into the parameter box, so inside the function, name holds "Mia".

TipParameter vs argument

These two words get mixed up all the time, even by professionals. Here's an easy way to remember:

  • A parameter is the placeholder in the function definition: function greet(name)
  • An argument is the actual value you pass in: greet("Mia")

P for Placeholder and Parameter. A for Actual and Argument.

Multiple parameters

A function can have as many parameters as you need. Separate them with commas:

JavaScript
function introduce(name, age, city) {
  console.log(`I'm ${name}, I'm ${age} years old, and I live in ${city}.`);
}

introduce("Sam", 14, "Cape Town");
introduce("Emma", 31, "Oslo");

It prints

I'm Sam, I'm 14 years old, and I live in Cape Town.
I'm Emma, I'm 31 years old, and I live in Oslo.

The arguments are matched to the parameters by position: the first argument goes into the first parameter, the second into the second, and so on. So the order matters:

JavaScript
introduce("Oslo", "Emma", 31);

It prints

I'm Oslo, I'm Emma years old, and I live in 31.

Emma is now a city, and Oslo is a person who is "Emma" years old. JavaScript doesn't know what you meant. It just matches things up in order.

Missing and extra arguments

What if you forget an argument?

JavaScript
function greet(name) {
  console.log(`Hello, ${name}!`);
}

greet();
greet("Sofia", "extra", "stuff");

It prints

Hello, undefined!
Hello, Sofia!

If you don't pass an argument, the parameter gets undefined (an empty box, just like in Grade 1). And if you pass too many arguments, the extras are simply ignored. JavaScript doesn't complain either way, so it's up to you to get it right.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning