Module 4: Functions, Scope, and Closures
Arrow Functions
Write concise callbacks and understand how arrow functions treat this.
Arrow functions provide a concise function syntax. They are commonly used for callbacks and short transformations.
const square = (number) => number * number;
const add = (a, b) => a + b;
const greet = name => `Hello, ${name}`;
An expression body returns its expression implicitly. Use braces for a statement body and return when a value is required:
const describe = (value) => {
const normalized = String(value).trim();
return `Value: ${normalized}`;
};
To implicitly return an object literal, wrap it in parentheses: const makeUser = name => ({ name });.
Important differences#
Arrow functions do not create their own this; they capture it lexically from the surrounding scope. They also do not have their own arguments object and cannot be used as constructors with new. A normal function is often preferable for object methods that rely on a dynamic this value.
Callbacks#
const numbers = [1, 2, 3];
const doubled = numbers.map(number => number * 2);
Arrow syntax is not automatically better for every function. Prefer the form that makes the behaviour and context easiest to understand.
Practice#
Rewrite a simple named function as an arrow function. Then create an object method and verify why a regular method may be more appropriate when it reads this.