FunctionsCore· 45 min read

Functions

Reusable blocks of code you can run any time. Functions are the heart of every program.

What you will learn

  • Define and call a function
  • Pass parameters and return values
  • Reuse logic instead of repeating it

Define once, use many times

A function is a named block of code you can run whenever you want. Define it with function, then call it with its name and ().

Define, then call (twice)
<script>
  function greet() {
    document.write("Hello, CodingClave!<br>");
  }
  greet();   // call it
  greet();   // call again
</script>
Live preview

The function greet() { ... } part only defines the recipe — nothing happens yet. Each greet() line below actually runs it. Because we call it twice, the message is written twice.

Note: Output: Hello, CodingClave! Hello, CodingClave!

Parameters and return

Parameters let you pass data in. return sends a result back out.

Parameters in, value returned out
<script>
  function add(a, b) {
    return a + b;
  }
  let result = add(5, 3);
  document.write("5 + 3 = " + result);
</script>
Live preview

add has two parameters, a and b — empty slots for incoming numbers. When we call add(5, 3), a becomes 5 and b becomes 3, and return a + b sends 8 back. That returned 8 lands in result, which we then print.

Note: Output: 5 + 3 = 8

The real power is reuse: the same function gives different answers for different inputs.

Same function, different inputs
<script>
  function greet(name) {
    return "Hello, " + name + "!";
  }
  document.write(greet("Asha") + "<br>");
  document.write(greet("Ravi"));
</script>
Live preview

greet("Asha") runs the function with name set to "Asha", returning "Hello, Asha!". The second call passes "Ravi", returning "Hello, Ravi!". One recipe, two different results — that is why functions save so much repeated typing.

Note: Output: Hello, Asha! Hello, Ravi!

Tip: Functions follow DRY — Do not Repeat Yourself. If you write the same lines twice, wrap them in a function and call it instead.

Q. What does the return keyword do?

Answer: return sends a result back to wherever the function was called, where you can store or use it.

✍️ Practice

  1. Write a function square(n) that returns n * n and call it with three numbers.
  2. Write a greet(name) function and call it for three people.

🏠 Homework

  1. Write a function that takes a price and a quantity and returns the total cost.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →