A JavaScript function expression is a way of defining a function. Even function expression can be stored in a variable. It can be to be stored in a variable and can be accessed using variableName.
Syntax
let sayHi = function() {
alert( "Hello" );
};
JavaScript function expression Examples
HTML example code variable can be used as a function in JavaScript.
Anonymous function (without name)
<!DOCTYPE html>
<html>
<head>
<script>
var multi = function (a, b) {return a * b};
var res = multi(7, 3);
alert (res);
</script>
</head>
<body>
</body>
</html>
Output:
Named function Expression
<script>
var calMul = function Mul(x, y){
let res = x * y;
return res;
}
console.log("Multiplication : " + calMul(7, 7));
</script>
Output: Multiplication : 49
Arrow Function
<script>
var calDiv = (x, y) => {
let res = x / y;
return res;
}
console.log("Division : " + calDiv(49, 7));
</script>
Output: Division : 7
Benefits of function expressions
A function expressions useful when:-
- As closures
- As Immediately Invoked Function Expressions (IIFE)
- As arguments to other functions
- A function expression can be stored in a variable:
Q: Why use named function expressions?
Answer: You should always use named function expressions, that’s why:
- You can use the name of that function when you need recursion.
- Anonymous functions don’t help when debugging as you can’t see the name of the function that causes problems.
- It’s harder to understand if you do not name a function.
Do comment if you have any doubts and suggestion on this topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version