Arrow Functions in JavaScript: A Simpler Way to Write Functions
Source: Dev.to
What Are Arrow Functions?
Arrow functions are a shorter way to write functions in JavaScript. Instead of using the function keyword, you use a fat arrow =>.
They’re not a replacement for every function — but for simple, focused tasks, they’re the cleaner choice.
Basic Arrow Function Syntax
Regular function
function greet(name) {
return "Hello, " + name + "!";
}Arrow function
const greet = (name) => {
return "Hello, " + name + "!";
};Syntax Breakdown
const greet = (name) => { return "Hello, " + name + "!"; };
// ↑ ↑ ↑ ↑
// variable params arrow function bodyArrow Functions with One Parameter
When you have exactly one parameter, you can drop the parentheses:
// With parentheses (always valid)
const square = (n) => {
return n * n;
};
// Without parentheses (one‑param shorthand)
const square = n => {
return n * n;
};
console.log(square(5)); // 25Both versions work; the second is just a little shorter.
Arrow Functions with Multiple Parameters
When you have two or more parameters, the parentheses are required:
const add = (a, b) => {
return a + b;
};
const multiply = (a, b) => {
return a * b;
};
console.log(add(3, 4)); // 7
console.log(multiply(3, 4)); // 12No parameters?
Use empty parentheses:
const sayHello = () => {
return "Hello, World!";
};Implicit Return vs Explicit Return
Explicit Return
Uses curly braces {} and the return keyword — just like regular functions:
const double = n => {
return n * 2; // explicit return
};Implicit Return
When the function body is a single expression, you can omit the braces and return keyword:
const double = n => n * 2; // implicit returnThey do exactly the same thing! The second version just skips the boilerplate.
More examples
const greet = name => "Hello, " + name + "!";
const isEven = n => n % 2 === 0;
const addTen = n => n + 10;
console.log(greet("Alice")); // Hello, Alice!
console.log(isEven(4)); // true
console.log(addTen(5)); // 15Important: Implicit return only works for a single expression. If you need multiple lines of logic, use curly braces and
return.
Normal Function vs Arrow Function
| Feature | Normal Function | Arrow Function |
|---|---|---|
| Syntax | function name() {} | const name = () => {} |
return keyword | Always needed | Optional (implicit return) |
| Hoisting | Hoisted | Not hoisted |
this keyword | Own this | Inherits this from parent |
| Best for | Methods, constructors | Short callbacks, transforms |
Transformation Example
// BEFORE (normal function)
function add(a, b) {
return a + b;
}
// AFTER (arrow function)
const add = (a, b) => a + b;Real-World Use: Arrow Functions Inside map()
Arrow functions shine as callbacks, for example inside map():
const numbers = [1, 2, 3, 4, 5];
// Normal function version
const doubled = numbers.map(function (n) {
return n * 2;
});
// Arrow function version — much cleaner!
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]