JavaScriptLesson 4 of 18

JavaScript Functions

A function is a block of code with a name. Write it once, then call it any time you need it, which means you never copy-paste the same lines twice. Real programs are built from small functions that each do one job. When a rule changes, you edit one spot and every call picks up the update.

A function is a block of code with a name. Write it once, then call it any time you need it, which means you never copy-paste the same lines twice. Real programs are built from small functions that each do one job. When a rule changes, you edit one spot and every call picks up the update.

A function can take input through parameters, listed in parentheses, and send output back with the return keyword. The function stops the moment it hits return, so anything after that line never runs. The most common beginner bug is forgetting the return line: the function runs, but the caller receives undefined instead of a value.

Give functions names that read like actions: calculateTotal, validateEmail, showError. The browser also provides ready-made functions, and you will call those constantly. One real-world use: a converter on a checkout page that recalculates the price the moment the quantity changes, without a page reload.

Parts of a function

Every function has a name, parentheses for parameters, and a body in curly braces. Declaring a function does not run it. You have to call it with its name and parentheses, like greet("Ada"). Forgetting the parentheses means the function never runs.

JS
function greet(name) {
  return "Hello, " + name;
}
greet("Ada"); // runs the function

Return stops the function

return does two jobs: it sends a value back and it ends the function. Use an early return to bail out of a function when the input is bad, before the rest of the code runs.

JS
function percent(part, whole) {
  if (whole === 0) {
    return 0; // stop early, avoid division by zero
  }
  return (part / whole) * 100;
}

Syntax

JS
function square(number) {
  return number * number;
}
const result = square(4); // 16

Forgetting return Gives undefined

A function without return hands back undefined — the #1 'why is my result undefined' bug.

JS
function square(n){ return n*n }

Good to know

  • A function bundles code under a name so you can reuse it.
  • Parameters are the input; return is the output.
  • Forgetting return makes a function hand back undefined.
  • return also stops the function, so you can bail out early.
Try it Yourself Edit the code, press Run, then check what changed in the Result.
Ready
Code
Result

Practice makes it stick

Open the Playground and build your own page with the tags you just learned.

→ Open Playground