Level: Intermediate | Player: 09_Destruction and_Spread
Learning Objectives
- Know the syntax of arrow functions.
- If the body is one line, use an implicit return.
- Can explain the difference between
functionandthisof the arrow. - Use arrow functions naturally as callbacks.
- Know when arrow functions are not appropriate (methods, constructors).
1. Basic grammar
const add = (a, b) => a + b;
const square = x => x * x; //If there is one parameter, parentheses can be omitted.
const log = () => console.log("hi"); //No arguments → empty parentheses
If the body has multiple lines, specify braces and return.
const greet = (name) => {
const msg = `Hello, ${name}`;
return msg;
};
2. Implicitly return an object
Object literals have the same appearance as function body blocks and must be enclosed in parentheses.
const make = (x, y) => ({ x, y });
3. this difference
this of general function is determined depending on the calling method, but arrow functions use this at the declared position (lexical this).
const obj = {
name: "A",
hello1: function () { return this.name; },
hello2: () => this?.name,
};
obj.hello1(); // "A"
obj.hello2(); //undefined (this at the time of declaration)
Therefore, object methods usually use function or shortened method syntax, and when you want to maintain an external this like a callback, you use an arrow.
4. Suitable for callbacks
[1, 2, 3].map((x) => x * 10); // [10, 20, 30]
setTimeout(() => console.log("done"), 100);
Core example
| file | Contents covered |
|---|---|
01_basic.js |
Basic syntax, parameter types |
02_implicit_return.js |
implicit return, return object |
03_this_diff.js |
this Compare the differences |
04_callbacks.js |
array method callback |
⚠️ Common Mistakes
- When returning an object, it is interpreted as a block by removing the parentheses and returns
undefined. - Define the arrow function as an object method and bewildered that
thisdoes not exist. - The arrow function forgets that there is no
argumentsobject. - Arrow functions cannot be called with the constructor (
new). - SyntaxError occurs by writing up to
returnin a one-line function.
❓ Frequently Asked Questions (FAQ)
Q1. Can I always use arrow functions? A. function is more appropriate for method and prototype definitions.
Q2. If arguments are needed? A. Use rest parameters (...args).
Q3. What is the difference from an anonymous function? A. Arrows are also anonymous, and are given a name by assigning them to a variable. However, the name attribute is inferred from the variable name.