JavaScript has three types of functions. A function should take some input and return an output where there is some logic between the input and the output.
Types of Functions in JavaScript
Simple example code of all types of functions available in JS.
Named function: Simply define it in the code and then call it. The below function returns the product of p1 and p2.
This is the most common way to define a function, using the function
keyword, followed by the function name and a set of parentheses.
<!DOCTYPE html>
<html>
<body>
<script >
function mult(p1, p2) {
return p1 * p2;
}
console.log(mult(20,50))
</script>
</body>
</html>
Output:
Anonymous function: is a function that does not have any name associated with it. A JavaScript function can also be defined using an expression.
A function expression is created by assigning a function to a variable. This allows you to define and use a function without giving it a name.
const x = function (a, b) {return a * b};
console.log(x(20,50))
Immediately invoked function expression: is a JavaScript function that runs as soon as it is defined.
An IIFE is a function that is executed immediately after it is defined. It is typically used to create a private scope for your code.
function()
{
console.log("Hello World");
})();
Arrow Function:
Arrow functions are a concise way to define functions, using =>
syntax. They are particularly useful for short, one-line functions.
const divideNumbers = (num1, num2) => num1 / num2;
Method Function:
Method functions are functions that are defined as a property of an object. They are used to encapsulate functionality that is specific to the object.
const person = {
name: "Jane",
greet: function() {
console.log("Hello, my name is " + this.name);
}
};
person.greet();
Do comment if you have any doubts or suggestions on this JS function topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version