function

Declares a named function that is hoisted within its scope.

Since ES1 Spec ↗

Syntax

function name(param1, param2) {
  // body
}

Returns

undefined — A function declaration is a statement and does not itself produce a value; calling the function may return a value.

Examples

function add(a, b) {
  return a + b;
}
console.log(add(2, 3));
Output
5
// Function declarations are hoisted
console.log(square(4));
function square(n) {
  return n * n;
}
Output
16
function greet(name = "world") {
  return "Hello, " + name;
}
console.log(greet());
Output
Hello, world

Notes

- Function declarations are hoisted with their definition, so they can be called before they appear in the source. - A function declaration creates a binding in the enclosing scope. - Use a function expression or arrow function when you need a function value assigned to a variable.

Browser & runtime support

EnvironmentSince version
chrome 1.0
firefox 1.0
safari 1.0
edge 12
node 0.10

See also