function

Declares a named function: a block of code with parameters that you can call any number of times and that can return a result.

On this page

Example

#
JavaScript
function calculateLevel(points) {
  return Math.floor(points / 100) + 1
}

console.log(calculateLevel(0))
console.log(calculateLevel(250))
Console
1
3

Definition and usage

#

A function declaration creates a function with the given name. A function is a recipe wrapped in a block: it takes data through parameters, runs statements, and can return a result with return. Once written, you call it as many times as you like.

Parameters can have default values, used when an argument isn’t passed. The rest parameter ...rest collects all the extra arguments into an array. A function that never runs return returns undefined.

Function declarations are hoisted in full, so you can call a function higher up in the file than where it’s written. This doesn’t apply to function expressions, e.g. const add = function () {}, which only work from the line of assignment onward.

Syntax

#
Syntax
function name(param1, param2) {
  // statements
  return value
}

function name(param = defaultValue, ...rest) {}

More examples

#
Default and rest parameters
JavaScript
function summary(student = 'Guest', ...scores) {
  const total = scores.reduce((sum, score) => sum + score, 0)
  return `${student}: ${total} pts`
}

console.log(summary('Emma', 10, 20, 30))
console.log(summary())
Console
Emma: 60 pts
Guest: 0 pts
Calling a function before its declaration
JavaScript
console.log(double(21))

function double(n) {
  return n * 2
}
Console
42
A function as an argument
JavaScript
function applyBonus(points, rule) {
  return rule(points)
}

function doubleBonus(points) {
  return points * 2
}

console.log(applyBonus(40, doubleBonus))
console.log(applyBonus(40, (points) => points + 5))
Console
80
45

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Name functions with verbs that say what they do: calculateTotal, formatDate, isValid. The code then reads almost like sentences.
  • A function should do one thing. If describing it needs the word “and,” consider splitting it into two smaller ones.
  • Missing arguments get the value undefined, and extra ones are ignored. JavaScript doesn’t report an error for the wrong number of arguments, so it’s worth validating the input.

Related entries

#

Spotted a mistake or missing an example? Write to us.