Arrow Functions
Arrow Functions
Section titled “Arrow Functions”Introduction
Section titled “Introduction”Arrow functions provide a concise syntax for writing functions. They also have a special behavior with the this keyword — they inherit this from the surrounding scope (lexical this).
Syntax
Section titled “Syntax”// Basicconst add = (a, b) => a + b;
// With block bodyconst add = (a, b) => { return a + b;};
// Single parameter — parentheses optionalconst square = x => x * x;
// No parametersconst greet = () => 'Hello!';Visual Explanation
Section titled “Visual Explanation”flowchart TD A["Arrow Functions"] B["const fn = (params) => expression"] C["✅ Concise syntax"] D["✅ Lexical this binding"] E["✅ Implicit return"] F["❌ No arguments object"] G["❌ Cannot be used as constructor"] H["❌ No prototype property"]
A --> B A --> C A --> D A --> E A --> F A --> G A --> HExamples
Section titled “Examples”// Implicit returnconst double = x => x * 2;
// With block body (explicit return needed)const sum = (a, b) => { const result = a + b; return result;};
// Returning an object literalconst createUser = (name, age) => ({ name, age });Lexical this
Section titled “Lexical this”const obj = { name: 'Alice', greet: function() { setTimeout(() => { console.log(this.name); // 'Alice' — arrow inherits this }, 100); }};Summary
Section titled “Summary”- Concise syntax with implicit return
- Lexical
this— inherits from surrounding scope - No
argumentsobject, nonewusage - Perfect for callbacks and array methods