Default Parameters

Grade 6, page 5 of 11. A one-minute read.

Sometimes you want a parameter to have a sensible value if the caller doesn't provide one. You can give it a default value with =:

JavaScript
function greet(name = "friend", emoji = "👋") {
  return `Hello, ${name}! ${emoji}`;
}

console.log(greet("Kenji", "🎉"));
console.log(greet("Chloe"));
console.log(greet());

It prints

Hello, Kenji! 🎉
Hello, Chloe! 👋
Hello, friend! 👋

If an argument is missing (or is undefined), the default is used instead. No more "Hello, undefined!"

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning