Arrow functions are a shorter way to write functions.
// normal function
const add = function (a, b) { return a + b; };
// arrow function
const add = (a, b) => a + b;
Rules
- One expression → the result is returned automatically (no
return, no braces) - One parameter → brackets are optional:
n => n * 2 - No parameters → empty brackets:
() => 'hi' - Several lines → use braces and
return - To return an object directly, wrap it:
() => ({ ok: true })
this
Arrow functions do not have their own this. They are great for callbacks (map, filter, setTimeout), but not for object methods that use this.
Example
Example — Arrow functions in practice
HTML
<pre id="out"></pre>
<script>
const square = n => n * n;
const greet = (name = 'Guest') => `Welcome, ${name}!`;
const toPrice = amount => {
const withTax = amount * 1.18;
return '₹' + withTax.toFixed(2);
};
const prices = [100, 250, 999].map(p => toPrice(p));
document.getElementById('out').textContent =
square(9) + '\n' + greet('Ravi') + '\n' + prices.join(', ');
</script>