AI Hints
JavaScript · Lesson 33 of 138

Default Parameters

Fallback values.

⏱ 2 min read▶ Video at 40:04🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

What happens if you call a function, but forget to pass an argument? The parameter is undefined, which can cause strange results. Default parameters give a fallback value instead.

Default Parameters
From the video: Default Parameters
  • Forgot an argument?
  • It's undefined
  • Defaults give a fallback

Equals in the brackets

Put an equals sign and a value after a parameter's name. If the caller doesn't pass that argument, the default is used. If they do, their value wins. Run it.

app.jsjavascript
function greet(name = "friend", greeting = "Hello") {
  return `${greeting}, ${name}!`;
}

console.log(greet());
console.log(greet("Ana"));
console.log(greet("Ben", "Good morning"));
Output
Hello, friend!
Hello, Ana!
Good morning, Ben!

Good defaults

Defaults make functions easier to use, because callers only pass what they need to change. Put parameters with defaults at the end of the list. And choose sensible defaults, the value most callers would want anyway.

keyvalue
name = 'friend'a default
Not passeddefault used
Passedtheir value wins
Orderdefaults last

Defaults that use other parameters

A default can use earlier parameters. Here, the height defaults to the width, so calling with one number makes a square. Defaults only kick in for missing or undefined arguments. Passing zero, or an empty string, keeps that value. Run it.

app.jsjavascript
function box(width, height = width) {
  return `${width} by ${height}`;
}

console.log(box(4));
console.log(box(4, 2));
console.log(box(4, undefined));
console.log(box(4, 0));
Output
4 by 4
4 by 2
4 by 4
4 by 0

Summary

Default parameters supply a value when an argument isn't passed. Next, a shorter way to write functions.

Key takeaways
  • param = value
  • Used when missing
  • Put defaults last
Next up: Arrow Functions — a shorter syntax