Junior
What is the difference between a traditional function and an arrow function in JavaScript?
sobes.tech AI
Answer from AI
The main difference lies in how they work with this.
A traditional function has its own this, which is determined by the context in which it is called (how it was invoked).
An arrow function does not have its own this. It lexically inherits this from the environment in which it was defined.
Other differences:
argumentsobject: Classic functions have access to theargumentsobject, arrow functions do not (but you can use rest parameters).- Constructors: Classic functions can be used as constructors with the
newoperator. Arrow functions cannot. prototypeproperty: Classic functions have aprototypeproperty. Arrow functions do not.
Example of working with this:
// Example with a classic function
const obj = {
name: 'Object',
greet: function() {
console.log(this.name); // this refers to obj
}
};
obj.greet(); // Outputs: Object
const greetFunc = obj.greet;
greetFunc(); // Outputs: undefined (or Window in browsers) - this loses the context of obj
// Example with an arrow function
const objArrow = {
name: 'Arrow Object',
greet: () => {
console.log(this.name); // this inherits context from outside (in this case global or Window)
}
};
objArrow.greet(); // Outputs: undefined (or Window name in browsers if name is defined globally)
const greetArrowFunc = objArrow.greet;
greetArrowFunc(); // Outputs: undefined (or Window name in browsers) - this does not change