JavaScript by Example

Function Parameters and this

Default parameters, rest parameters, and the dynamic this value that regular functions receive from the call site.

Parameters are the inputs a function declares. JavaScript gives you a few tools for optional inputs, many inputs, and object-method calls.

Default parameters set a fallback value when the caller omits an argument or passes undefined.

function connect(host = "localhost", port = 5432) {
  console.log(host + ":" + port);
}
 
connect();                // localhost:5432
connect("db.prod", 5433); // db.prod:5433
connect("db.prod");       // db.prod:5432

A rest parameter collects any number of extra arguments into a real array. Write it with three dots before the parameter name. It must come last.

function greetAll(greeting, ...names) {
  for (const name of names) {
    console.log(greeting + ", " + name + "!");
  }
}
 
greetAll("Hello", "Ana", "Ben", "Carl");
// Hello, Ana!
// Hello, Ben!
// Hello, Carl!

this is a special value inside regular functions. It comes from how the function is called. A method call sets this to the object before the dot. A direct call has no object, so this is undefined in strict mode.

const counter = {
  count: 0,
  increment() {
    this.count++;
    console.log(this.count);
  },
};
 
counter.increment(); // 1, this is counter
 
const fn = counter.increment;
fn(); // TypeError, this is undefined

In production

Positional parameters past two or three make call-sites unreadable: createUser("Ana", true, false, null, 3). Prefer an options object: createUser({ name, admin, verified, role, retries }). It survives reordering and lets callers omit optional fields cleanly.

Enjoyed this? Get more software craft delivered to your inbox.