Skip to content
  • Parameters, Defaults & Rest · JavaScript

Parameters, Defaults & Rest

LearnViaNotes @learnvianotes· 2 min read

JavaScript never checks argument counts: missing ones are undefined, extras are ignored — defaults, rest parameters and destructuring make that manageable.

Missing and extra arguments

JavaScript
function show(a, b) {
  console.log(a, b, arguments.length);
}
show(1);
show(1, 2, 3);
Output
1 undefined 1
1 2 3

Default parameters

JavaScript
function greet(name = "guest", greeting = `Hello, ${name}`) {
  return greeting;
}
console.log(greet());
console.log(greet("Asha"));
console.log(greet(undefined, "Hey"));   // undefined triggers the default
console.log(greet(null));               // null does not
Output
Hello, guest
Hello, Asha
Hey
Hello, null
JavaScript
function append(item, list = []) {
  list.push(item);
  return list;
}
console.log(append(1), append(2));
let counter = 0;
const next = (id = ++counter) => id;
console.log(next(), next(), next(99), next());
Output
[ 1 ] [ 2 ]
1 2 99 3

Rest parameters vs arguments

JavaScript
function oldStyle() {
  console.log(Array.isArray(arguments), Array.from(arguments));
}
function modern(first, ...rest) {
  console.log(first, rest, Array.isArray(rest));
}
oldStyle(1, 2);
modern(1, 2, 3);
modern(1);
Output
false [ 1, 2 ]
1 [ 2, 3 ] true
1 [] true
arguments...rest
TypeArray-like object (no map)Real array
In arrow functionsNot availableWorks
ContainsAll argumentsOnly the remaining ones
Position—Must be the last parameter

Named options via destructuring

JavaScript
function createUser({ name, role = "viewer", active = true } = {}) {
  return `${name} (${role}${active ? "" : ", inactive"})`;
}
console.log(createUser({ name: "Ravi" }));
console.log(createUser({ name: "Mei", role: "admin", active: false }));
console.log(createUser());
Output
Ravi (viewer)
Mei (admin, inactive)
undefined (viewer)

What is the arguments object?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report