Turning def Into function
In this lesson, you ported the crew’s describe_dock() function to JavaScript, then added the free
slots to it and saw what happens to a call that wasn’t updated.
- Where Python writes
def, JavaScript writes a function declaration, one way to write a named function: the keywordfunction, the name in camelCase, and the parameters in parentheses, as in Python. - Braces mark the body, because JavaScript doesn’t read indentation, as with
ifand loops. returnhands the value back, as in Python.- JavaScript doesn’t require a call to pass every argument. A parameter with no argument starts out
as
undefined, and a template literal turns it into the textundefined. Where Python stops with aTypeErrorwhen it reaches the call, JavaScript runs and prints a wrong line. - A function that ends without a
returngives backundefined, where Python givesNone. - JavaScript doesn’t stop at the call the way Python does, so when you change a function’s
parameters, update every call, then run the file and read the output. An
undefinedin a line means a value that was never passed, or a return that’s missing. - Python lets you give a parameter a default, and JavaScript can too. Defaults and keyword arguments come later.
Here’s the port with the free slots added, where the Elm Street call wasn’t updated:
function describeDock(name, bikes, slots) {
return `${name}: ${bikes} bikes, ${slots} free`;
}
console.log(describeDock("Elm Street", 0));
console.log(describeDock("Harbor Square", 14, 1));
console.log(describeDock("Station Road", 6, 8));
console.log(describeDock("Market Hall", 0, 10));
console.log(describeDock("Riverside Park", 11, 2));