Functions: declarations, parameters and return values

Package code into reusable functions, pass in values with parameters and defaults, return results, and store functions in variables.

  • Beginner
  • 8 min read
  • Updated 17 Oct 2026

What you will learn

  • Write functions with parameters
  • Return values from functions
  • Set default parameter values
  • Explain the difference between function declarations and function expressions

A function is a named, reusable piece of code. Instead of repeating the same steps in several places, you write them once and call the function whenever you need them. Functions are the main building block of every JavaScript program, so this lesson is one of the most important in the course.

Declaring and calling a function

A function declaration starts with the function keyword, a name, brackets and a body in braces:

JavaScript
function sayHello() {
  console.log("Hello!");
}

sayHello();
// Hello!
sayHello();
// Hello!

Declaring a function does not run it. You call it by writing its name followed by brackets. Forgetting the brackets is a common slip: sayHello on its own refers to the function without running it.

Name functions after what they do, usually starting with a verb: calculateTotal, showMessage, isValidEmail.

Parameters and arguments

Functions become useful when you can pass values into them. Parameters are the names listed in the brackets of the declaration. Arguments are the actual values you pass when you call it:

JavaScript
function greet(name) {
  console.log(`Hello, ${name}!`);
}

greet("Ada");
// Hello, Ada!
greet("Grace");
// Hello, Grace!

Here name is the parameter, and "Ada" and "Grace" are arguments. Inside the function, a parameter behaves like a variable that holds the argument.

Separate several parameters with commas. Arguments are matched to parameters by position:

JavaScript
function describe(name, role) {
  console.log(`${name} is a ${role}.`);
}

describe("Ada", "mathematician");
// Ada is a mathematician.
describe("mathematician", "Ada");
// mathematician is a Ada.

Missing and extra arguments

JavaScript does not check how many arguments you pass. A missing argument is undefined, and extra arguments are ignored:

JavaScript
greet();
// Hello, undefined!
greet("Ada", "extra");
// Hello, Ada!

That flexibility hides mistakes, so check that you call functions with the arguments they expect. Lesson 23 shows how to collect any number of arguments with rest parameters.

Default parameters

Give a parameter a default value with =. The default is used when the argument is missing or undefined:

JavaScript
function greet(name = "friend") {
  console.log(`Hello, ${name}!`);
}

greet();
// Hello, friend!
greet("Ada");
// Hello, Ada!

Defaults only replace undefined. Passing null, 0 or "" uses that value, which is usually what you want:

JavaScript
function setVolume(level = 50) {
  return level;
}

console.log(setVolume());
// 50
console.log(setVolume(0));
// 0

Returning values

Most functions should calculate something and return it, rather than logging it. return sends a value back to wherever the function was called:

JavaScript
function calculateTotal(price, quantity) {
  return price * quantity;
}

const total = calculateTotal(4.5, 3);
console.log(total);
// 13.5

The call calculateTotal(4.5, 3) is replaced by the value it returns, so you can use it anywhere a value fits:

JavaScript
console.log(`Total: £${calculateTotal(4.5, 3).toFixed(2)}`);
// Total: £13.50

Returning values makes functions far more useful than logging inside them. The caller decides what to do with the result: show it, store it, or pass it to another function.

return ends the function

return stops the function straight away. Code after it does not run:

JavaScript
function getShipping(total) {
  if (total >= 50) {
    return 0;
  }
  return 4.99;
}

console.log(getShipping(60));
// 0
console.log(getShipping(20));
// 4.99

This is the guard clause pattern you saw in lesson 8: handle a special case and return early.

Functions without return

A function with no return, or a bare return;, returns undefined:

JavaScript
function logTwice(message) {
  console.log(message);
  console.log(message);
}

const result = logTwice("Hi");
// Hi
// Hi
console.log(result);
// undefined

Do not put a line break straight after return. JavaScript inserts a semicolon there automatically, so return followed by a value on the next line returns undefined. If a returned expression is long, open a bracket on the same line as return.

Variables inside functions

Variables declared inside a function exist only inside it. They are created fresh on every call and disappear when the function finishes:

JavaScript
function makeLabel(count) {
  const noun = count === 1 ? "item" : "items";
  return `${count} ${noun}`;
}

console.log(makeLabel(3));
// 3 items
console.log(noun);
// Uncaught ReferenceError: noun is not defined

A function can read variables from outside it, but relying on outside variables makes a function harder to reuse and test. Prefer passing in what the function needs as parameters and returning what it produces. Lesson 19 covers scope in full.

Function expressions

Functions are values in JavaScript. You can store a function in a variable, just like a number or a string. This is a function expression:

JavaScript
const square = function (n) {
  return n * n;
};

console.log(square(4));
// 16

The function has no name of its own here; the variable square refers to it. Because it is a value, you can also pass a function to another function. A function passed in this way is called a callback:

JavaScript
function repeat(times, action) {
  for (let i = 0; i < times; i++) {
    action(i);
  }
}

repeat(3, function (i) {
  console.log(`Pass ${i}`);
});
// Pass 0
// Pass 1
// Pass 2

Callbacks are everywhere in JavaScript. Event listeners, array methods and timers all take a function to call later. The next lesson introduces arrow functions, a shorter syntax that is usually used for callbacks.

Declarations versus expressions

The main practical difference is hoisting. You can call a function declaration before the line where it is written, because declarations are processed before the rest of the code runs:

JavaScript
console.log(double(5));
// 10

function double(n) {
  return n * 2;
}

A function expression stored in a const is not available until that line has run:

JavaScript
console.log(triple(5));
// Uncaught ReferenceError: Cannot access 'triple' before initialization

const triple = function (n) {
  return n * 3;
};

Both styles are common. Declarations suit the main, named functions of a file. Expressions and arrow functions suit callbacks and functions you pass around. Lesson 19 explains hoisting properly.

Writing good functions

  • Do one thing. A function called validateAndSaveAndEmail should be three functions.
  • Return values instead of logging them. Keep showing results separate from calculating them.
  • Keep the parameter list short. More than three parameters is hard to call correctly; lesson 23 shows how to pass an options object instead.
  • Use clear names for the function and its parameters, so a call reads clearly without looking up the definition.

Here is a small function that follows those rules:

JavaScript
function formatPrice(pence, currency = "£") {
  return `${currency}${(pence / 100).toFixed(2)}`;
}

console.log(formatPrice(1999));
// £19.99
console.log(formatPrice(500, "€"));
// €5.00

Summary

  • Declare functions with function name(params) { ... } and call them with name(args).
  • Parameters are matched to arguments by position. Missing arguments are undefined; extra ones are ignored.
  • Default parameters replace missing or undefined arguments.
  • return sends a value back and ends the function. Without it, a function returns undefined.
  • Functions are values: you can store them in variables and pass them as callbacks.
  • Function declarations are hoisted; function expressions in a const are not usable before their line.

Further reading