In Javascript, functions can also be defined as expressions.
The function
keyword can be used to define a function inside an expression.
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 has to be stored in a variable and can be accessed using variableName.
Functions stored in variables do not need function names. They are always invoked (called) using the variable name.
Syntax for Function Declaration
function functionName(x, y) { statements... return (z) }
Syntax for Function Expression (anonymous)
let variableName = function(x, y) { statements... return (z) };
You might wonder, why does Function Expression have a semicolon ;
at the end, but Function Declaration does not.
- The semicolon would be there for a simpler assignment, such as
let var = 5;
, and it’s also there for a function assignment. - The semicolon
;
is recommended at the end of the statement, it’s not a part of the function syntax.
A function expression has to be defined first before calling it or using it as a parameter.
Example
const getRectArea = function(width, height) {
return width * height;
};
console.log(getRectArea(3, 4));
// expected output: 12
In the above program, variable getRectArea is used to store the function. Here the function is treated as an expression. And the function is called using the variable name.
The function above is called an anonymous function.
A function expression can be used as an IIFE (Immediately Invoked Function Expression)which runs as soon as it is defined.