Returning Two Results at Once
Python’s quote() hands back the fee and the turnaround with return fee, days: for the
6,200-word contract without the rush, the tuple (744.0, 5), which the caller unpacks with fee, days = quote(6200).
- The comma loses the fee. Ported line by line,
return fee, days;makesconsole.log(quote(6200))log only5, with no error. JavaScript has no tuples: its comma is an operator that evaluates both sides and keeps the last value. Parentheses don’t help:return (fee, days);still gives5. - The caller fails instead.
const [fee, days] = quote(6200);throwsTypeError: quote is not a function or its return value is not iterable, at line 8. A number isn’t iterable, and Python’sfee, days = 5stops the same way. The real slip is in thereturn, which ran without a word, so when destructuring fails, read the function’sreturnfirst. - The fix is an array. It logs
[ 744, 5 ], with no.0: JavaScript numbers don’t split into integers and floats. It does the tuple’s job here, a pair read by position, though nothing stops code from changing it.
function quote(words) {
const fee = Math.max(words * 0.12, 40);
const days = 2 + Math.floor(words / 2000);
return [fee, days];
}
console.log(quote(6200));
const [fee, days] = quote(6200);
console.log(fee, days);
It logs the array, then the fee and the days:
[ 744, 5 ]
744 5
The JavaScript way: an array when the caller unpacks a pair right away, an object when the results deserve names, which the caller reads by name, not by position (the short way to write it comes later in this course).
Next up: Work Out a Fee and a Turnaround, an exercise.