~/
hackweb.dev
JavaScript Arrow Functions
Quiz
⌘K
...
~/
/tutorials
/js/js-arrow-functions/edit
~ Contribute
Suggest a correction or improvement. The author reviews it before it goes live.
Loading...
Comment
0 / 300
Typo
Grammar
Broken link
Clarify
Code
en/tutorials/js/9js-arrow-functions
Write
Preview
Diff
# JavaScript Arrow Functions Arrow functions provide a shorter syntax for functions and unique `this` behavior. ## What Are Arrow Functions? A concise way to write function expressions: ```javascript // Traditional let greet = function(name) { return `Hello, ${name}!`; }; // Arrow let greet = (name) => `Hello, ${name}!`; ``` ## Syntax Variations ```javascript // One parameter — parentheses optional let double = x => x * 2; // Multiple parameters — parentheses required let add = (a, b) => a + b; // Multiple statements — braces + explicit return let complex = (x) => { let result = x * 2; return result; }; ``` **Remember:** Single expression = implicit return. Multiple statements = use `{}` and `return`. ## No `this` Binding Arrow functions inherit `this` from the outer scope: ```javascript let person = { name: "John", greet() { console.log(`Hello, I'm ${this.name}`); // "John" }, greetArrow: () => { console.log(`Hello, I'm ${this.name}`); // undefined } }; ``` **Tip:** Never use arrow functions as object methods — `this` won't point to the object. ## Arrow Functions in Callbacks ```javascript let numbers = [1, 2, 3, 4, 5]; let doubled = numbers.map((n) => n * 2); let evens = numbers.filter((n) => n % 2 === 0); ``` ## Complete Example: Filter and Transform ```javascript let users = [ { name: "Alice", age: 25 }, { name: "Bob", age: 17 }, { name: "Charlie", age: 30 } ]; let adults = users.filter((user) => user.age >= 18); let names = adults.map((user) => user.name.toUpperCase()); console.log(names); // ["ALICE", "CHARLIE"] ``` ## Promise Handling ```javascript fetchData("https://api.example.com") .then((data) => console.log(data)) .catch((error) => console.log(error)); ``` ## Best Practices 1. **Use for callbacks** — cleaner syntax 2. **Use regular functions for methods** — so `this` works 3. **Use implicit return for simple functions** — more concise ## Common Mistakes 1. **Using arrow functions as object methods** — `this` is wrong 2. **Using arrow functions as constructors** — they can't be used with `new` 3. **Using `arguments` object** — arrow functions don't have it 4. **Forgetting parentheses with multiple parameters** — syntax error
No changes yet
Reset to original
Submit suggestion
cancel