Making Every Option Optional

Your port of quote() now takes its options by name, and Bauer Legal’s rush job comes out at €1,116.00 in two working days, as it does in Python. The next request is Café Linde’s 180-word menu. The café didn’t tick a single box on the form, so the call is quote(180), with no options at all.

Python handles that without a second thought, because every optional parameter has a default. Your JavaScript port can’t take that call yet, because its pattern expects an object and there isn’t one. In this lesson, you’ll make the whole options object optional, pass options on without repeating their names, and decide which parameters belong in the object at all.

Leave the Options Out

The translator’s Python function gives every optional parameter a default, so a call with only the word count is complete:

Language: Python
def quote(words, rate=0.12, rush=False, minimum=40):
    fee = max(words * rate, minimum)
    days = 2 + words // 2000
    if rush:
        return fee * 1.5, max(1, days // 2)
    return fee, days

print(quote(180))

Python prints (40, 2), the minimum fee and the shortest normal turnaround. In the JavaScript port, the destructuring pattern from the last lesson gets one more default, = {}, after its closing brace:

Language: JavaScript
function quote(
  words,
  { rate = 0.12, rush = false, minimum = 40 } = {},
) {
  const fee = Math.max(words * rate, minimum);
  const days = 2 + Math.floor(words / 2000);
  if (rush) {
    return [fee * 1.5, Math.max(1, Math.floor(days / 2))];
  }
  return [fee, days];
}

console.log(quote(180));
console.log(quote(6200, { rush: true }));

Run it, and the café gets its €40 minimum while Bauer Legal keeps its rush price:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.