AnyCompiler

Functions

A function is a named, reusable block of code. Anywhere you find yourself writing similar code more than once, that's usually a sign it should be a function instead.

function greet(name) {
  return `Hello, ${name}!`;
}

console.log(greet("Alice"));
console.log(greet("Bob"));
Output
Hello, Alice!
Hello, Bob!
  • function starts a function declaration, followed by its name and parameters in parentheses
  • return sends a value back to wherever the function was called — without it, a function returns undefined
  • name is a parameter — a placeholder that gets filled in with whatever you pass when you call the function

Default parameters

You can give a parameter a default value, making it optional — callers can leave it out entirely, or override it when they need something different.

function greet(name, greeting = "Hello") {
  return `${greeting}, ${name}!`;
}

console.log(greet("Alice"));
console.log(greet("Bob", "Hi"));
Output
Hello, Alice!
Hi, Bob!

Next: arrow functions — a shorter syntax for writing functions.

Practice exercise

Write a function square(n) that returns n * n, then print square(6).