JavaScript Reference ยท Statements and Declarations
The function declaration
Reference for the JavaScript function declaration: syntax, parameters, hoisting, block-level functions, function expressions versus declarations, and examples.
A function declaration creates a named function and binds it to a name in the current scope. The declaration is hoisted: you can call the function in code that appears above it in the same scope.
Functions are objects, so you can pass them around, store them in variables and give them properties.
function greet(name) { return `Hello, ${name}!`; }
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
function name(param1, param2 = defaultValue, ...rest) { statements }
| Name | Description |
|---|---|
name |
The function name. Required in a declaration (except export default function). The name is bound in the enclosing scope. |
param1, param2 |
Parameters. May have default values, be destructuring patterns, or end with a rest parameter. |
statements |
The function body. It returns undefined unless a return statement provides a value. |
Usage notes
- Hoisting. Both the name and the body are available from the top of the enclosing scope. Function expressions and arrow functions assigned to
letorconstare not; they stay in the temporal dead zone until their line runs. - Scope. In strict mode and in modules, a function declared in a block is scoped to that block. In sloppy-mode scripts, legacy rules also make it visible outside the block in some cases; avoid declaring functions inside blocks and
ifstatements. - Redeclaring a function with the same name in one scope silently replaces the earlier one in sloppy mode. Avoid it.
this. A normal function gets its ownthis, decided by how it is called. Arrow functions takethisfrom where they are written.Function.lengthcounts parameters before the first default or rest parameter;nameholds the declared name.- Constructors. A function declaration can be called with
new, but classes are the modern way to build constructors. Methods, arrow functions, generators and async functions cannot be used withnew. - Naming. Use verbs for actions (
parseInput) and keep functions short and focused on one job. - Parameters are by value. Objects are passed as references to the same object, so mutating a parameter's properties is visible to the caller.
Browser support
The function declaration works in every engine. Default and rest parameters are supported by all current browsers.