There are mainly two advantages of JavaScript functions.
1. Code reusability: We can call a function several times so it save coding.
2. Less coding: It makes our program compact. We don’t need to write many lines of code each time to perform a common task.
There are three type of function
- Named function
- Anonymous function
- Immediately invoked function expression
Syntax:
function function-name(argumants, ----){
statement;
}
Named Function
Named function is the function that we define it in the code and then call it whenever we need it by referencing its name and passing some arguments to it. Named functions are useful if we need to call a function many times to pass different values to it or run it several times.
function myFunction(a, b) {
return a * b;
}
Anonymous function
The function above is actually an anonymous function (a function without a name). Functions stored in variables do not need function names. They are always invoked (called) using the variable name.
A JavaScript function can also be defined using an expression.
const x = function (a, b) {return a * b};
let z = x(4, 3);
Functions can also be defined with a built-in JavaScript function constructor called Function()
const myFunction = new Function('a', 'b', 'return a * b');
let x = myFunction(4, 3);
const myFunction = function (a, b) {return a * b};
let x = myFunction(4, 3);
Immediately invoked function expression
Function expressions can be made 'self-invoking'. A self-invoking expression is invoked (started) automatically. Function expressions will execute automatically if the expression is followed by (). You cannot self-invoke a function declaration. You have to add parentheses around the function to indicate that it is a function expression.
(function () {
console.log('Hello! I called myself');
})();