In the last lesson, you wrote countdown(n, announce) and handed it sayCount. Every call so far has started from 3, yet each one still has to say so. Tomás’s helpers are full of settings like that. They’re the same almost every time, but not quite always.
In this lesson, you’ll give parameters values that JavaScript uses when a call leaves them out. You’ll be able to predict when such a value applies and when it doesn’t, and you’ll add one to a helper without breaking the calls you’ve already written. Start with the snack bill, which Tomás splits the same way nearly every movie night.
Give a Parameter a Default
Most movie nights, Tomás, Aisha, Priya, Kenji, and Lucía share the snacks, so they split the bill five ways. Tomás pays at the shop, and a small helper tells him what each friend owes. Save this first version as snacks.js:
snacks.js
function snackShare(total, friends) {
return total / friends;
}
console.log(`Five friends: ${snackShare(30, 5)}`);
console.log(`Count left out: ${snackShare(30)}`);
Run it, and the second call goes wrong without any complaint:
$ node snacks.js
Five friends: 6
Count left out: NaN
When a call leaves out an argument, its parameter starts as undefined. Dividing 30 by undefined gives NaN, short for “Not a Number,” and JavaScript doesn’t raise an error about it. So on a normal night, Tomás has to remember to type the 5.
A default parameter removes that chore. You write = value after the parameter’s name, and JavaScript uses that value whenever the call leaves the argument out. Change the helper’s first line and the two calls:
snacks.js
function snackShare(total, friends = 5) {
return total / friends;
}
console.log(`Normal night: ${snackShare(30)}`);
console.log(`Three friends: ${snackShare(30, 3)}`);
This time, both calls give a sensible share:
$ node snacks.js
Normal night: 6
Three friends: 10
The first call has no second argument, so friends starts as 5. The second call passes 3, which wins over the default. A call that already passed 5, like snackShare(30, 5), still works exactly as before. Arrow functions take defaults the same way: const snackShare = (total, friends = 5) => total / friends;.
Why does friends come second? Arguments still fill parameters in order, left to right, and a default doesn’t change that. In snackShare(30), the 30 goes to the first parameter, whatever its name. So a parameter the caller may leave out belongs after the ones they must always pass. The total changes every night, so it comes first. The number of friends rarely changes, so it goes last.
Know When the Default Applies
A default fills a gap, so you need to know exactly what JavaScript counts as a gap. JavaScript uses the default only when the parameter would otherwise be undefined. That happens when the call leaves the argument out or when it passes undefined itself. Any other value replaces the default, even one that looks empty.
Tomás also hands out snack jobs, and whoever hasn’t picked anything brings popcorn. Type this session into the REPL and compare each result with the rule:
> const assignSnack = (name, snack = "popcorn") =>
… `${name} brings ${snack}`;
undefined
> assignSnack("Aisha")
'Aisha brings popcorn'
> assignSnack("Kenji", undefined)
'Kenji brings popcorn'
> assignSnack("Priya", null)
'Priya brings null'
> assignSnack("Lucía", "")
'Lucía brings '
Aisha and Kenji both get the default. For a default, leaving an argument out and passing undefined count as the same thing.
Priya’s null is a real value, one that means “nothing” on purpose. It isn’t undefined, so the default stays out, and the template literal turns it into the text null. Lucía’s empty string is falsy, but falsiness isn’t what the default checks. Only undefined counts, so Lucía brings an empty string.
If you want null or "" to mean popcorn too, a default can’t do that for you. You’d check for those values with an if in the function’s body.
Putting the difference into your own words is a quick way to find out whether it has stuck. The button below opens a chat with the mentor, with the start of a sentence already typed in. Finish it with your own reason before you send it, and the mentor will tell you whether your explanation holds up and help with any gap:
Work Out a Default From the Call
Some settings don’t have one fixed value. When the snacks are delivered, Tomás tips the driver, usually a tenth of the order, so the usual tip changes with the order.
Besides a fixed value like 5, a default can be any expression. JavaScript works it out at the moment of each call that needs it, so the expression can use the parameters to its left and can call a function. Save this script as tips.js. The console.log() in suggestTip shows you each time the function runs:
tips.js
const suggestTip = (snacks) => {
console.log(`Working out a tip for ${snacks}`);
return snacks / 10;
};
const addTip = (snacks, tip = suggestTip(snacks)) =>
snacks + tip;
console.log(`Friday: ${addTip(30)}`);
console.log(`Saturday: ${addTip(40)}`);
console.log(`Sunday: ${addTip(40, 5)}`);
Run it and read the output line by line:
$ node tips.js
Working out a tip for 30
Friday: 33
Working out a tip for 40
Saturday: 44
Sunday: 45
On Friday and Saturday, suggestTip ran during the call, with that call’s snacks, so each night got its own tip. The default isn’t worked out once, when you write the function. On Sunday, Tomás passed a tip of 5, so suggestTip never ran, and the output has no “Working out” line before Sunday: 45.
The default can use snacks because snacks comes first. Parameters get their values left to right, so among the parameters, a default can rely only on the ones before it. MDN’s Default parameters page has more examples of what a default can contain.
Before you move on, check that you can predict and write defaults. Work out the first one in your head before you run anything. Then use the REPL or a script for both:
- Using
addTipfromtips.js, predict whataddTip(20, 0)andaddTip(20, undefined)each log and return. - In
countdown.js, givecountdowndefaults so thatcountdown()alone counts down from 3 withsayCount, whilecountdown(3, sayCount)keeps working. Why doescountdown()need a default for both parameters, not only forn?
addTip(20, 0)returns20and logs nothing. Zero is falsy, but it’s notundefined, so the tip is0andsuggestTipnever runs.addTip(20, undefined)logsWorking out a tip for 20and returns22, because an explicitundefinedlets the default run.- Give both parameters a default:
countdown.js
function countdown(n = 3, announce = sayCount) {
for (let count = n; count > 0; count--) {
announce(count);
}
}
function sayCount(number) {
console.log(`${number}...`);
}
countdown();
A call with no arguments now counts from the default:
$ node countdown.js
3...
2...
1...
The empty call countdown() passes no arguments at all, so both n and announce start as undefined. With only n = 3, the loop would still try to call announce(count), and calling undefined stops the script with a TypeError. The default for announce is a function value, sayCount without parentheses, so countdown always has a function to call.
The order rule from the first section still holds here. Optional parameters go after the ones a caller must pass. Here both are optional, and n comes first because it’s the one a caller is more likely to change. A different start, like countdown(5), keeps sayCount.
If your prediction for addTip(20, 0) didn’t match the result, it helps to find the exact step where your reasoning went off. Use the button below to tell the mentor how you worked out your prediction, and they’ll walk through it with you:
The next item is the course’s first coding exercise, and it runs in your browser, not in your terminal. You write code in the editor on the page, then click Run Tests or press Cmd+Enter or Ctrl+Enter. Automated tests check what your functions return.
The results show which tests pass. A failing test or an error message tells you what went wrong, so read it for clues before you change your code. Run the tests early and often, after each small change. If the editor feels cramped, Full screen gives it the whole window.
A default lets a helper cover the usual case on its own, while the caller can still pass something else. Next, in Exercise: Write Movie-Night Helpers, you’ll get Tomás’s helpers ready for the evening. You’ll write one that formats each film’s runtime for the shortlist, a countdown to the film’s start, and snackShare(total, friends = 5), which splits the snack bill on a normal night without being told how many friends came.