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:
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".
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:
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:
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?
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.