Arrow functions (`=>`) provide a shorter syntax and **lexical this** — they don't create their own `this` context but inherit it from where they are defined. They cannot be used as constructors, don't have `arguments` objects, and can't be generators.
1Understanding Arrow Functions
Arrow functions (=>) provide a shorter syntax and lexical this — they don't create their own this context but inherit it from where they are defined. They cannot be used as constructors, don't have arguments objects, and can't be generators.
Use arrow functions for callbacks and short expressions. Use regular functions for methods, constructors, and when you need 'this' binding.
// Concise syntax forms
const add = (a, b) => a + b; // two params, expression body
const sq = x => x * x; // one param, no parens
const pi = () => 3.14159; // no params
const log = msg => { console.log('[LOG]', msg); }; // block body
console.log(add(3, 5)); // 8
console.log(sq(7)); // 492Practical Example
Here is a real-world application of Arrow Functions showing how it is used in production JavaScript code.
// Lexical 'this' - key difference
function Timer() {
this.seconds = 0;
// Arrow function captures 'this' from Timer()
setInterval(() => {
this.seconds++;
}, 1000);
}
// In a regular function callback, 'this' would be window/undefined3Best Practices
Follow these guidelines when working with Arrow Functions:
1. Omit parentheses for single parameters
2. Omit braces and return for single-expression bodies
3. Never use arrow functions as object methods if you need 'this'
Tip: Use arrow functions for callbacks and short expressions. Use regular functions for methods, constructors, and when you need 'this' binding.
// Concise syntax forms
const add = (a, b) => a + b; // two params, expression body
const sq = x => x * x; // one param, no parens
const pi = () => 3.14159; // no params
const log = msg => { console.log('[LOG]', msg); }; // block body
console.log(add(3, 5)); // 8
console.log(sq(7)); // 49