Course outline · 0% complete

0/29 lessons0%

Course overview →

Declaring functions

lesson 6-1 · ~9 min · 18/29

Quiz

Warm-up from lesson 5-3: which call turns the text '{"a":1}' into a live object you can read with dots?

def becomes function

Functions remain the unit of reuse in any language: name a computation once, call it everywhere, test it in isolation. Every JavaScript codebase you will ever read is mostly function definitions, so this unit makes writing them automatic.

A Python function:

def greet(name):
    return f"Hello, {name}!"

The same function in JavaScript:

function greet(name) {
  return `Hello, ${name}!`;
}

The pieces map one-to-one: the keyword is function, parameters sit in parentheses, the body sits in braces, and return sends a value back. Calling is identical: greet("Ada").

Default parameter values work like Python too: function area(w, h = 2) uses 2 whenever h is not passed. One difference to know: calling with too few arguments does not raise an error like Python's TypeError. The missing parameter is simply undefined, so bugs surface later rather than immediately.

A function with no return (or a bare return;) gives back undefined, the same role as Python's None.

Code exercise · javascript

Run it. greet returns a string, area shows a default parameter filling in when the second argument is missing.

Code exercise · javascript

Your turn. Write a function celsiusToF(c) that returns c × 9/5 + 32. Print the result for 0 and for 100.

Returning early

return does two jobs at once: it hands back a value AND stops the function immediately. Professionals lean on that to reject special cases first — a check-and-return at the top of a function is called a guard clause — so the main logic below stays flat instead of nesting inside else after else:

function describe(age) {
  if (age < 0) {
    return "Invalid age";
  }
  if (age < 18) {
    return "Minor";
  }
  return "Adult";
}

Once a return runs, nothing after it in the function does. No else is needed: merely reaching the second if proves the age was not negative.

Code exercise · javascript

Your turn. Write checkUsername(name) with two guard clauses: names shorter than 3 characters return Too short, names containing a space return No spaces allowed, everything else returns OK. Print the result for "al", "ada lovelace", and "ada".

Quiz

function ping() { console.log("ping"); } What does console.log(ping()) print AFTER ping itself prints?