JavaScript
JavaScript functions can be classified into several types based on how they are defined and used. Here are some of the most common types of JavaScript functions:
- Function Declarations:
-
These are the most basic type of function in JavaScript, declared using
the
function
keyword followed by the function name, parameter list and function body enclosed in curly braces. - They can be called anywhere within the scope of the function definition.
Example:
function add(x, y) {
return x + y;
}
- Function Expressions:
- These are similar to function declarations, but are assigned to a variable or a property of an object.
- They are also referred to as anonymous functions since they do not have a function name.
- They are called by using the variable or property name they are assigned to.
Example:
const add = function(x, y) {
return x + y;
};
- Arrow Functions:
- These are a shorthand syntax for function expressions that were introduced in ES6.
-
They use the
=>
operator instead of thefunction
keyword, and do not have their ownthis
orarguments
keywords. - They are ideal for writing concise and readable code.
- They are called in the same way as function expressions.
Example:
const add = (x, y) => {
return x + y;
};
- Methods:
- These are functions that are defined as properties of an object.
-
They can access the object's properties using the
this
keyword. - They are called by referencing the object property they are defined on.
Example:
const calculator = {
add: function(x, y) {
return x + y;
}
};
calculator.add(2, 3); // returns 5
- Callback Functions:
- These are functions that are passed as arguments to another function, and are called when the main function completes its execution.
- They are commonly used in asynchronous programming, event handling and functional programming.
Example:
const printResult = function(callback) {
const result = 2 + 3;
callback(result);
};
printResult(function(result) {
console.log(result); // logs 5
});
These are just a few of the many types of functions available in JavaScript, and they can be combined in various ways to create complex and powerful applications.