Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 3.3 — Default, Rest Parameters and Spread
JavaScript · Example 1 of 3

Default parameters: when they apply

Only undefined triggers a default. nextId(50) doesn't need the default, so ++calls doesn't run for it.

Default parameters fill in missing arguments, rest parameters (...items) collect any number of arguments into an array, spread (...array) does the opposite at the call, and destructured parameters pull named options straight out of an object; the old arguments object still exists in regular functions.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write power(base, exponent = 2) that returns base ** exponent. Test power(5) and power(2, 10).

02

Write joinWords(separator, ...words) so that joinWords("-", "a", "b", "c") returns "a-b-c".

03

Write formatPrice({ amount, currency = "₹", decimals = 2 } = {}) that returns the currency followed by the amount with that many decimals, e.g. "₹49.90".

Explain it without notes

01

When does a default parameter value get used, and when is it evaluated?

02

What is the difference between a rest parameter and spread syntax?

03

What is the arguments object, and why are rest parameters preferred today?

04

Why do APIs often accept a single destructured options object instead of many positional parameters?

Default parameters: when they apply

Console

(nothing was printed)

Expected console output

Hello, friend!
Hello, Asha!
Hi, Asha!
Hey, friend!
Hello, null!
Hello, !
110 100
1 2 50 3