- JavaScript Functions
- Example
- JavaScript Function Syntax
- Function Invocation
- Function Return
- Example
- Why Functions?
- The () Operator
- Example
- Example
- Example
- Note
- Functions Used as Variable Values
- Example
- Local Variables
- Example
- Function expression
- Try it
- Syntax
- Parameters
- Description
- Function expression hoisting
- Named function expression
- Examples
- Creating an unnamed function
- Using a function as a callback
- Using an Immediately Invoked Function Expression (IIFE)
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
JavaScript Functions
A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is executed when «something» invokes it (calls it).
Example
JavaScript Function Syntax
A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
The parentheses may include parameter names separated by commas:
(parameter1, parameter2, . )
The code to be executed, by the function, is placed inside curly brackets: <>
Function parameters are listed inside the parentheses () in the function definition.
Function arguments are the values received by the function when it is invoked.
Inside the function, the arguments (the parameters) behave as local variables.
Function Invocation
The code inside the function will execute when «something» invokes (calls) the function:
- When an event occurs (when a user clicks a button)
- When it is invoked (called) from JavaScript code
- Automatically (self invoked)
You will learn a lot more about function invocation later in this tutorial.
Function Return
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will «return» to execute the code after the invoking statement.
Functions often compute a return value. The return value is «returned» back to the «caller»:
Example
Calculate the product of two numbers, and return the result:
// Function is called, the return value will end up in x
let x = myFunction(4, 3);
function myFunction(a, b) // Function returns the product of a and b
return a * b;
>
Why Functions?
With functions you can reuse code
You can write code that can be used many times.
You can use the same code with different arguments, to produce different results.
The () Operator
The () operator invokes (calls) the function:
Example
Convert Fahrenheit to Celsius:
function toCelsius(fahrenheit) <
return (5/9) * (fahrenheit-32);
>
Accessing a function with incorrect parameters can return an incorrect answer:
Example
function toCelsius(fahrenheit) <
return (5/9) * (fahrenheit-32);
>
Accessing a function without () returns the function and not the function result:
Example
function toCelsius(fahrenheit) <
return (5/9) * (fahrenheit-32);
>
Note
As you see from the examples above, toCelsius refers to the function object, and toCelsius() refers to the function result.
Functions Used as Variable Values
Functions can be used the same way as you use variables, in all types of formulas, assignments, and calculations.
Example
Instead of using a variable to store the return value of a function:
You can use the function directly, as a variable value:
You will learn a lot more about functions later in this tutorial.
Local Variables
Variables declared within a JavaScript function, become LOCAL to the function.
Local variables can only be accessed from within the function.
Example
// code here can NOT use carName
function myFunction() let carName = «Volvo»;
// code here CAN use carName
>
// code here can NOT use carName
Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.
Local variables are created when a function starts, and deleted when the function is completed.
Function expression
The function keyword can be used to define a function inside an expression.
You can also define functions using the function declaration or the arrow syntax.
Try it
Syntax
function (param0) statements > function (param0, param1) statements > function (param0, param1, /* … ,*/ paramN) statements > function name(param0) statements > function name(param0, param1) statements > function name(param0, param1, /* … ,*/ paramN) statements >
Note: An expression statement cannot begin with the keyword function to avoid ambiguity with a function declaration. The function keyword only begins an expression when it appears in a context that cannot accept statements.
Parameters
The function name. Can be omitted, in which case the function is anonymous. The name is only local to the function body.
The name of an argument to be passed to the function.
The statements which comprise the body of the function.
Description
A function expression is very similar to, and has almost the same syntax as, a function declaration. The main difference between a function expression and a function declaration is the function name, which can be omitted in function expressions to create anonymous functions. A function expression can be used as an IIFE (Immediately Invoked Function Expression) which runs as soon as it is defined. See also the chapter about functions for more information.
Function expression hoisting
Function expressions in JavaScript are not hoisted, unlike function declarations. You can’t use function expressions before you create them:
.log(notHoisted); // undefined // Even though the variable name is hoisted, // the definition isn't. so it's undefined. notHoisted(); // TypeError: notHoisted is not a function var notHoisted = function () console.log("bar"); >;
Named function expression
If you want to refer to the current function inside the function body, you need to create a named function expression. This name is then local only to the function body (scope). This avoids using the deprecated arguments.callee property to call the function recursively.
const math = factit: function factorial(n) console.log(n); if (n 1) return 1; > return n * factorial(n - 1); >, >; math.factit(3); //3;2;1;
If a function expression is named, the name property of the function is set to that name, instead of the implicit name inferred from syntax (such as the variable the function is assigned to).
Unlike declarations, the name of the function expressions is read-only.
function foo() foo = 1; > foo(); console.log(foo); // 1 (function foo() foo = 1; // TypeError: Assignment to constant variable. >)();
Examples
Creating an unnamed function
The following example defines an unnamed function and assigns it to x . The function returns the square of its argument:
const x = function (y) return y * y; >;
Using a function as a callback
More commonly it is used as a callback:
.addEventListener("click", function (event) console.log("button is clicked!"); >);
Using an Immediately Invoked Function Expression (IIFE)
An anonymous function is created and called:
(function () console.log("Code runs!"); >)(); // or !function () console.log("Code runs!"); >();
Specifications
Browser compatibility
BCD tables only load in the browser
See also
- Arrow functions
- Functions
- Function object
- function statement
- function* statement
- function* expression
- GeneratorFunction object
- async function declaration
- async function expression
Found a content problem with this page?
This page was last modified on Jul 3, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.