JS Arrow Functions
Arrow functions are a shorter syntax for writing functions. Beyond being terse, they have one important behavioural difference: they don't have their own this.
The three forms
JS
// Single expression — implicit return
const double = (x) => x * 2;
// Single param — parentheses optional
const square = x => x * x;
// Multiple statements — needs braces and explicit return
const greet = (name) => {
const msg = `Hi, ${name}!`;
return msg;
};
// Returning an object literal — wrap in parens
const point = (x, y) => ({ x, y });
Arrow vs. regular function
| Feature | Arrow | Regular |
|---|---|---|
Own this | No — inherits enclosing scope | Yes — set by call site |
Own arguments | No | Yes |
| Hoisted? | No | Declarations: yes |
Usable with new | No | Yes |
| Best for | Callbacks, methods on classes (often) | Top-level functions, methods that need this |
The this behaviour matters
JS
class Counter {
constructor() { this.count = 0; }
// ✅ Arrow uses the Counter instance as `this`
increment = () => { this.count++; };
// ❌ A regular method passed as a callback loses its `this`
incrementBad() { this.count++; }
}
const c = new Counter();
setTimeout(c.increment, 100); // works ✓
setTimeout(c.incrementBad, 100); // breaks ✗ — this is undefined
Tip: Reach for arrow functions for everything except object methods that should be re-bindable, constructors, and generator functions. They're the modern default for callbacks.
Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Arrow Functions!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Return an object literal from an arrow without using a function body.
const point = (x, y) =>
{ x, y })
Wrap the literal so the braces are not seen as a block.
Discussion
Loading…