- Array() find
- -- operator
- -= operator
- ++ operator
- += operator
- Accessing and setting content
- AND operator
- Array concat() method
- Array indexOf()
- Array length
- Array pop()
- Array shift
- Array slice() method
- Arrays
- Arrow function
- Async await
- Booleans
- Braces
- Callback function
- Calling the function
- Class
- Closure
- Code block
- Comment
- Conditions
- Console
- const
- Constructor
- Creating a p element
- Data types
- Date getTime()
- Destructuring
- DOM
- Else
- Else if
- Enum
- Environment
- Equals operator
- Error Handling
- ES6
- Event listener method
- Event loop
- Events
- Export statement
- Extends
- Fetch API
- Filter
- For loop
- forEach()
- Function
- Function bind()
- Function name
- Greater than
- Head element
- Hoisting
- If statement
- Import statement
- includes()
- Infinity property
- isNaN function
- Iterator
- JSON
- Less than
- Let
- Local storage
- Map
- Methods
- Module
- Modulo operator
- Node.js
- null
- Numbers
- Object
- Object.keys()
- Optional chaining
- Overriding methods
- Parameters
- Promises
- Prototype
- Random
- Reduce
- Regex
- Regular expressions
- Removing an element
- Replace
- Scope
- Session storage
- setInterval
- setTimeout() method
- Sleep() function
- Sort
- Splice
- Spread operator
- String
- String concat()
- String indexOf()
- String slice() method
- Substring
- Switch statement
- Template literals
- Ternary operator
- throw Statement
- Title
- Try catch
- Type conversion
- undefined
- var
- void Operator
- What is JavaScript?
- While loop
JAVASCRIPT
JavaScript Arrow Function: Syntax, Usage, and Examples
An arrow function is a shorter way to write a function in JavaScript. It’s popular in modern ES6 code because it keeps your logic compact and often makes callbacks easier to read.
How to Use an Arrow Function
Arrow functions use the => (arrow) syntax. You can write them as a single expression or as a full block with curly braces.
Learn JavaScript on Mimo
Basic syntax
constgreet = () => {
console.log("Hi!");
};
That creates a function and stores it in the greet variable.
Arrow function with parameters
Add parameters inside the parentheses.
constgreetUser = (name) => {
console.log(`Hi, ${name}!`);
};
greetUser("Amina");
If you have one parameter, you can skip the parentheses:
constshout = message => {
console.log(message.toUpperCase());
};
shout("hello");
Arrow function with an implicit return
If the body is only one expression, you can remove curly braces and the return keyword. The value is returned automatically.
constadd = (a, b) => a + b;
console.log(add(2,5));// 7
This is called an implicit return.
Arrow function with a block body
If you use curly braces, you need to write return yourself.
constadd = (a, b) => {
return a + b;
};
A small rule to remember: curly braces mean you’re in full function-body mode, so no automatic return.
Returning an object
This one catches a lot of people the first time.
If you try to return an object with an implicit return, you need parentheses around the object. Otherwise JavaScript thinks the {} is a function block.
✅ Correct:
constcreateUser = (name) => ({name: name,role:"member" });
console.log(createUser("Luka"));
❌ Wrong:
// const createUser = (name) => { name: name };
// This returns undefined, because it is treated like a block
Arrow functions and this
Arrow functions don’t create their own this. They inherit this from the surrounding scope, which is called lexical this.
That’s helpful when you want this to refer to the outer object or class.
const profile = {
name:"Nora",
sayHi:function () {
setTimeout(() => {
console.log(`Hi, I am ${this.name}`);
},500);
}
};
profile.sayHi();
Using a regular function inside setTimeout() often breaks this, but an arrow function keeps it pointing to profile.
When to Use an Arrow Function
Arrow functions shine in a bunch of real-world patterns. They are not meant to replace every function you write, but they’re perfect for some jobs.
1) When you write callbacks
Callbacks show up everywhere, like in map(), filter(), find(), and event handlers. Arrow functions keep these short and readable.
const scores = [10,25,7,40];
const doubled = scores.map(score => score *2);
console.log(doubled);
That’s easier on the eyes than writing function(score) { ... } every time.
2) When you want a concise function for small logic
Tiny functions like “add numbers” or “format a label” are great candidates for arrow functions.
constformatPrice = price =>`€${price.toFixed(2)}`;
console.log(formatPrice(9.5));
The code stays compact without feeling cramped.
3) When you want this from the outer scope
Arrow functions are useful inside class methods, object methods, or nested functions where you still want the outer this.
This happens a lot when you use timers or async code.
classTimer {
constructor() {
this.seconds =0;
}
start() {
setInterval(() => {
this.seconds++;
console.log(this.seconds);
},1000);
}
}
const t =newTimer();
t.start();
4) When you work with functional patterns
Modern JavaScript leans into functional-style helpers like reduce() and chaining.
Arrow functions work naturally in that style.
const cart = [
{item:"Notebook",price:5 },
{item:"Pen",price:2 },
{item:"Mug",price:8 }
];
const total = cart.reduce((sum, product) => sum + product.price,0);
console.log(total);
Examples of an Arrow Function
Example 1: Filtering items in an array
This example keeps only the products that are in stock.
const products = [
{name:"Keyboard",inStock:true },
{name:"Mouse",inStock:false },
{name:"Monitor",inStock:true }
];
const available = products.filter(product => product.inStock);
console.log(available);
Arrow functions are perfect here because the logic is short and the intention is clear.
Example 2: Sorting names alphabetically
Sorting often needs a small comparison function. Arrow functions make that easy.
const names = ["Jelena","Amir","Sofia","Tariq"];
names.sort((a, b) => a.localeCompare(b));
console.log(names);
Example 3: Mapping data into new shapes
Here’s a common pattern when you prepare data for display.
const users = [
{name:"Kai",points:120 },
{name:"Marta",points:80 },
{name:"Sam",points:150 }
];
const labels = users.map(user =>`${user.name}:${user.points} pts`);
console.log(labels);
Example 4: Returning an object for UI rendering
Many UI frameworks expect an object or structured data.
constmakeCardData = (title, description) => ({
title: title,
description: description,
pinned:false
});
console.log(makeCardData("Quick Tips","Arrow functions are handy."));
That object return syntax is a small detail, but it shows up constantly.
Example 5: Using arrow functions with events
Arrow functions are commonly used as event callbacks.
<buttonid="saveBtn">Save</button>
<script>
const button =document.querySelector("#saveBtn");
button.addEventListener("click",() => {
console.log("Saved!");
});
</script>
That’s a clean pattern for quick interactions.
Learn More About an Arrow Function
Arrow function vs function declaration
Arrow functions are not the same as traditional functions. They behave differently in a few important ways.
1) this binding
A regular function gets its own this depending on how it’s called. An arrow function inherits this from where it was created.
That’s why this works well:
const playlist = {
name:"Focus Beats",
playLater() {
setTimeout(() => {
console.log(`Playing: ${this.name}`);
},300);
}
};
playlist.playLater();
2) Arrow functions can’t be used as constructors
You can use regular functions with new, but arrow functions don’t have their own this, so they can’t be constructors.
// const Person = (name) => { this.name = name };
// new Person("Lana"); // TypeError
Use a class or a normal function instead.
3) Arrow functions don’t have arguments
Regular functions have an arguments object you can use to access passed values.
Arrow functions don’t have that. If you need “any number of arguments,” use rest parameters (...args) instead.
constsumAll = (...numbers) => {
return numbers.reduce((sum, n) => sum + n,0);
};
console.log(sumAll(1,2,3,4));
Common arrow function mistakes
Forgetting return in block bodies
This returns undefined because there’s no return statement.
constmultiply = (a, b) => {
a * b;
};
console.log(multiply(3,4));// undefined
Fix it like this:
constmultiply = (a, b) => {
return a * b;
};
Or use an implicit return:
constmultiply = (a, b) => a * b;
Confusing object return syntax
This returns an object correctly:
constmakeUser = name => ({name: name });
This does not:
// const makeUser = name => { name: name };
Arrow functions in real apps
Arrow functions show up constantly in:
- React components and handlers
- API response mapping
- array utilities and transformations
- async code with promises
Here’s a quick promise example:
fetch("https://example.com/api/items")
.then(res => res.json())
.then(data =>console.log(data))
.catch(err =>console.log("Request failed:", err));
When not to use an arrow function
Arrow functions are great, but sometimes a regular function is a better choice.
- You need a function that acts as a constructor.
- You need dynamic
thisbased on how the function is called. - You are writing a method on an object and you want
thisto refer to the object when called.
For example, this is better as a normal function:
const counter = {
count:0,
increment:function () {
this.count++;
}
};
If you wrote increment as an arrow function, this would not point to counter.
Summary
An arrow function is a modern JavaScript syntax for writing functions with =>. It’s ideal for callbacks and small helper functions, and it keeps this from the outer scope. Learn the key differences, especially this, implicit returns, and object return syntax, and you’ll be able to read and write modern JavaScript much faster.
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot