Path: blob/main/files/en-us/web/javascript/reference/statements/function/index.md
6520 views
------{{jsSidebar("Statements")}}
The function declaration defines a function with the specified parameters.
You can also define functions using the {{jsxref("Function")}} constructor and a {{jsxref("Operators/function", "function expression", "", 1)}}.
{{EmbedInteractiveExample("pages/js/statement-function.html","shorter")}}
Syntax
name: The function name.
param{{optional_inline}}: The name of an argument to be passed to the function. Maximum number of arguments varies in different engines.
statements{{optional_inline}}: The statements which comprise the body of the function.
Description
A function created with a function declaration is a Function object and has all the properties, methods and behavior of Function objects. See {{jsxref("Function")}} for detailed information on functions.
A function can also be created using an expression (see {{jsxref("Operators/function", "function expression", "", 1)}}).
By default, functions return undefined. To return any other value, the function must have a {{jsxref("Statements/return", "return")}} statement that specifies the value to return.
Block-level function declaration
Warning: In non-strict mode, function declarations inside blocks behave strangely. Only declare functions in blocks if you are in strict mode.
Functions can be conditionally declared — that is, a function statement can be nested within an if statement. However, in non-strict mode, the results are inconsistent across implementations.
The scoping and hoisting effect won't change regardless of whether the if body is actually executed.
In strict mode, block-level function declarations are scoped to that block and are hoisted to the top of the block.
Function declaration hoisting
Function declarations in JavaScript are hoisted to the top of the enclosing function or global scope. You can use the function before you declared it:
Note that {{jsxref("Operators/function", "function expressions", "", 1)}} are not hoisted:
Examples
Using function
The following code declares a function that returns the total amount of sales, when given the number of units sold of three products.
Specifications
{{Specifications}}
Browser compatibility
{{Compat}}
See also
{{jsxref("Function")}}
{{jsxref("Operators/function", "function expression", "", 1)}}
{{jsxref("Statements/function*", "function* statement", "", 1)}}
{{jsxref("Operators/function*", "function* expression", "", 1)}}
{{jsxref("Functions/Arrow_functions", "Arrow functions", "", 1)}}
{{jsxref("GeneratorFunction")}}
{{jsxref("Statements/async_function", "async function", "", 1)}}
{{jsxref("Operators/async_function", "async function expression", "", 1)}}