Function Basics

Defining and Calling a Function

Example

A function is a reusable block of code. Define it once, call it as often as needed:

function greet(name) {
  return "Hello, " + name + "!";
}
console.log(greet("Asha"));
console.log(greet("Vikram"));

Output

Hello, Asha!
Hello, Vikram!

Return Values

Example

return sends a value back and ends the function. A function without return returns undefined:

function area(w, h) {
  return w * h;
  console.log("never runs");
}
function logOnly(x) {
  console.log("got", x);
}
console.log(area(4, 5));
console.log(logOnly(1));

Output

20
got 1
undefined

Why Functions?

  • Reuse: write the logic once.
  • Abstraction: give a name to an idea (calculateTax) and hide the details.
  • Testing: small functions with clear inputs and outputs are easy to test.