Functions: wrap and reuse logic

What a function is; parameters, return, reuse.

1. What is this?

A function is a named, reusable block. Parameters are the inputs you declare (function greet(name)), arguments are the values you pass when calling (greet("Ava")). return sends a value back to the caller. Without return, the function does its job but gives nothing back.

2. Why do we use it?

Names, totals, validations repeat across an app. Functions let you write logic once, name it well, and call it anywhere.

3. Syntax breakdown

  • function greet(name) {

    Declares a function called greet that accepts one input, name.

  •   return "Hello, " + name;

    Builds a greeting and sends it back to whoever called.

  • console.log(greet("Ava"));

    Calls greet with "Ava", then prints the returned string.

5. Common mistakes

  • Forgetting return — the function runs but console.log gets undefined.
  • Calling greet() with no argument, so name is undefined.
  • Confusing console.log inside a function (a side effect) with return (a value).

Practice task

Write a function double(n) that returns n * 2. Log double(7).

Hint

function double(n) { return n * 2; } then console.log(double(7));

Try it below — tests run automatically when you press Run.

javascript

Output

Press Run to see output.

Mini quiz

3 questions. Answer, then check.

  1. 1. What is a parameter?

  2. 2. What does return do?

  3. 3. What prints if a function has no return and you log its call?

4. Example — edit and run

javascript

Output

Press Run to see output.

Expected output: Hello, Ava