← JavaScript tutorial

JavaScript

Functions

A function is a reusable block of code. Define it once, then call it by name wherever you need it, passing different arguments each time.

Example 1: a standard function declaration

function greet(name) {
  return "Hello, " + name + "!";
}

document.getElementById("output").textContent = greet("Chidi");

return sends a value back out of the function to wherever it was called from — without it, calling greet("Chidi") would still run the code inside, but the result would be undefined everywhere else.

Example 2: the shorter arrow function syntax

const square = (n) => n * n;
const greetArrow = (name) => "Hi, " + name + "!";

document.getElementById("output").textContent =
  greetArrow("Ada") + " Square of 6 is " + square(6);

Arrow functions are a more compact syntax for the same idea — a one-line arrow function with no curly braces automatically returns its expression, no explicit return keyword needed. You'll see arrow functions constantly in modern JavaScript, especially for short functions passed as arguments to other functions, which the Arrays lesson shows next.

Try it yourself