Back
LearnJavaScript From ZeroWhy do we need functions?

Why do we need functions?

2 min read

Doing the same thing again and again? Stop.

Say you greet three people:

console.log("Hello Riya, welcome!");
console.log("Hello Sam, welcome!");
console.log("Hello Neha, welcome!");

Same sentence, copied three times. If you later want to change "welcome" to "good morning", you must edit every single line. This is where a function saves you.

A function is a named block of code that you write once and reuse whenever you want.

How do I make one?

function greet(name) {
  console.log("Hello " + name + ", welcome!");
}
  • function → "I am making a reusable block".
  • greet → the name we give it.
  • (name) → an empty slot we fill in each time (this is called a parameter).

Now call it as many times as you like:

greet("Riya");
greet("Sam");
greet("Neha");

Three lines, one source of truth. Change the sentence once inside greet, and all three update together.

What is "return"?

Sometimes a function should give back an answer instead of just printing it. That is what return does.

function add(a, b) {
  return a + b;
}

let total = add(5, 3);   // total is now 8
console.log(total);

add hands back 8, and we store it in total. Printing is for humans to see; return is for the program to use.

Think of a function like a kitchen machine: you put ingredients in (parameters), it does the work, and hands you a finished dish back (return).

Tip