Pass Values Into a Function
JavaScript Function Parameters
Parameters are the named inputs of a function. JavaScript is forgiving — extra args are ignored, missing ones are `undefined`.
What you'll learn
- Define parameters and pass arguments
- Understand pass-by-value vs reference behavior
- Know what happens with too few or too many arguments
A parameter is a name in a function declaration. An argument is the value you pass when you call the function.
function greet(name, age) { // name and age are parameters
console.log(`${name} is ${age}`);
}
greet("Ada", 36); // "Ada" and 36 are arguments Too Few Arguments
If the caller forgets an argument, the parameter is undefined —
no error.
function greet(name, age) {
console.log(`${name} is ${age}`);
}
greet("Ada");
// "Ada is undefined" This is a common bug source. The next lesson covers default parameters, which let you handle missing values gracefully.
Too Many Arguments
Extra arguments are silently ignored.
function add(a, b) {
return a + b;
}
console.log(add(1, 2, 3, 4, 5)); // 3 ← only a, b matter If you actually want to accept a variable number of arguments, see rest parameters in a couple of lessons.
Pass by Value (Primitives)
When you pass a primitive (string, number, boolean), the function gets a copy of the value. Changes inside don’t affect the caller.
function tryToChange(n) {
n = 999;
console.log("inside:", n);
}
let x = 5;
tryToChange(x);
console.log("outside:", x);
// inside: 999
// outside: 5 ← unchanged Pass by Reference (Objects & Arrays)
Objects and arrays are passed by reference — the function gets the same object, so mutations are visible to the caller.
function addItem(cart, item) {
cart.push(item); // mutates the original!
}
const cart = ["apple"];
addItem(cart, "bread");
console.log(cart); // ["apple", "bread"] Reassigning vs Mutating
If you reassign the parameter, the caller doesn’t see it. If you mutate the object the parameter points at, they do.
function reassign(obj) {
obj = { x: 999 }; // reassigning the local name — invisible to caller
}
function mutate(obj) {
obj.x = 999; // mutating the shared object — visible
}
const a = { x: 1 };
reassign(a);
console.log(a); // { x: 1 }
const b = { x: 1 };
mutate(b);
console.log(b); // { x: 999 } The arguments Object (Legacy)
Inside a regular function, the special arguments object holds all
the values that were passed in.
function showAll() {
console.log(arguments.length);
for (let i = 0; i < arguments.length; i++) {
console.log(arguments[i]);
}
}
showAll("a", "b", "c");
// 3
// "a"
// "b"
// "c" Up Next
Defaulting a parameter when the caller leaves it out.
JavaScript Default Parameters →