Difficulty: Beginner
What are arrow functions in JavaScript? How do they differ from regular functions?
Arrow functions (=>) are a concise syntax for writing functions introduced in ES6. They differ from regular functions in several key ways:
1. No own "this" - arrow functions inherit "this" from the enclosing lexical scope 2. No "arguments" object - use rest parameters (...args) instead 3. Cannot be used as constructors - cannot use "new" keyword 4. No prototype property 5. Cannot be used as generator functions 6. Implicit return for single expressions
// Regular function
function add(a, b) { return a + b; }
// Arrow function variations
const add1 = (a, b) => a + b; // implicit return
const add2 = (a, b) => { return a + b; }; // explicit return
const square = x => x * x; // single param, no parens needed
const greet = () => "Hello!"; // no params
const getObj = () => ({ name: "JS" }); // return object literal
console.log(add1(2, 3));
console.log(square(4));
console.log(greet());
console.log(getObj());
Arrow functions can have implicit returns and various parameter styles.
const obj = {
name: "Timer",
startRegular: function() {
setTimeout(function() {
console.log("Regular:", this.name); // undefined
}, 100);
},
startArrow: function() {
setTimeout(() => {
console.log("Arrow:", this.name); // "Timer"
}, 100);
}
};
obj.startRegular(); // Regular: undefined
obj.startArrow(); // Arrow: Timer
The regular function callback gets its own "this" (global/undefined). The arrow function inherits "this" from startArrow, which is obj.
Arrow Functions, this Binding, Lexical Scope, ES6