JavaScript has several types of functions, including:
Function Declarations:
Function declarations define named functions with optional parameters and a function body.
Example:
function myFunction(parameter1, parameter2) {
// function body
}
Function Expressions:
Function expressions create functions anonymously and assign them to variables.
Example:
var myFunction = function(parameter1, parameter2) {
// function body
};
Arrow Functions:
Arrow functions are a concise way to write function expressions in ES6. They have a simplified syntax and a lexical this binding.
Example:
const myFunction = (parameter1, parameter2) => {
// function body
};
Immediately Invoked Function Expressions (IIFE):
IIFEs are functions that are executed immediately after they are defined. They are useful for creating private variables and functions.
Example:
(function() {
// function body
})();
Methods:
Methods are functions that are defined as properties of objects. They can be called on the object they belong to using the dot notation.
Example:
var myObject = {
myMethod: function(parameter1, parameter2) {
// function body
}
}; myObject.myMethod(parameter1, parameter2);
Callback Functions:
Callback functions are functions that are passed as arguments to another function and are executed when the function completes its task.
Example:
function myFunction(callback) {
// function body
callback();
}
myFunction(function() {
// callback function body
});