function
In JavaScript, the function keyword defines a function, either as a declaration that binds a name in the enclosing scope or as an expression that produces a function value. Function declarations are hoisted together with their body, so code can call them before the line where they appear.
Function expressions aren’t hoisted. A function expression can have its own name, which is visible only inside its body and lets the function call itself. A statement that starts with function is always a declaration, so an IIFE wraps the expression in parentheses.
Unlike arrow functions, regular functions get their own this binding and can be called with new. Writing function* defines a generator function, added in ES2015, whose body pauses at each yield. Prefixing either form with async creates an async function. Every function is an instance of Function.
JavaScript function Keyword Syntax
The function keyword defines declarations, expressions, and generator functions:
function <name>([<parameters>]) {
<statements>
}
const <binding> = function [<name>]([<parameters>]) {
<statements>
};
function* <name>([<parameters>]) {
<statements>
}
The * form also works as an expression, and export default accepts a declaration without a name.
JavaScript function Keyword Examples
A function declaration can be called before it appears, while a named function expression keeps its name to itself:
greet.mjs
console.log(greet("Ada"));
function greet(name) {
return `Hello, ${name}!`;
}
const factorial = function fact(n) {
return n <= 1 ? 1 : n * fact(n - 1);
};
console.log(factorial(5));
console.log(typeof fact);
Running the file prints three lines:
$ node greet.mjs
Hello, Ada!
120
undefined
The call to greet() works before its declaration because of hoisting. The name fact exists only inside the function expression, so typeof fact outside it is "undefined".
Calling a generator function returns a generator object, which produces one value per yield:
> function* countdown(start) {
… for (let n = start; n > 0; n -= 1) {
… yield n;
… }
… }
undefined
> [...countdown(3)]
[ 3, 2, 1 ]
Spreading the generator collects every value it yields.
JavaScript function Keyword Use Cases
- Declaring named functions that can be called anywhere in their scope
- Passing a function expression as a callback or storing it in a variable
- Writing recursive function expressions that refer to themselves by name
- Defining generator functions that produce values lazily
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.
By Leodanis Pozo Ramos • Updated Nov. 4, 2026