Types of Function
Types of Function
Types of Function
1. **Function Declarations**:
```javascript
function myFunction() {
// code to be executed
}
```
2. **Function Expressions**:
```javascript
const myFunction = function() {
// code to be executed
};
```
5. **Anonymous Functions**:
These are functions without a name and are often used as arguments to other
functions.
```javascript
setTimeout(function() {
console.log("Executed after 1 second");
}, 1000);
```
6. **Named Functions**:
These are functions that have a name and can be called by that name.
```javascript
function namedFunction() {
// code to be executed
}
```
7. **Higher-Order Functions**:
Functions that take other functions as arguments or return them.
```javascript
function higherOrderFunction(callback) {
callback();
}
```
Each type of function has its own use cases and advantages, depending on the
requirements of the code you are writing.
Arrow functions in JavaScript do not have their own `this` context; instead, they
lexically bind `this` from the surrounding scope. This means that when you use an
arrow function, it takes `this` from the enclosing function or context in which it
is defined. Here are a few reasons why this design choice is beneficial:
```javascript
const obj = {
name: 'Eve',
greet: function() {
const inner = () => {
console.log(`Hello, ${this.name}`);
};
inner(); // Uses `this` from `greet`, which refers to `obj`
}
};
obj.greet(); // Hello, Eve
```
```javascript
const array = [1, 2, 3];
const obj = {
multiplier: 2,
double: function() {
return array.map(value => value * this.multiplier); // `this` refers to
`obj`
}
};
console.log(obj.double()); // [2, 4, 6]
```
4. **No `this` Binding Needed**: With arrow functions, you don't need to use
`bind`, `call`, or `apply` to set the correct context, making your code cleaner and
easier to read.
However, it's essential to remember that this behavior makes arrow functions
unsuitable for situations where you do want to create a new `this` context, such as
in object methods or when using them as constructors. In those cases, you should
use regular function expressions.