Whether you’re working with React , Next.js or Node.js, there are a few JavaScript methods that become your everyday tools. These are essential for writing efficient , clean and readable code.
In this blog , we will break down the most commonly used JavaScript methods like .map() , .filter(), .reduce() , >includes() , .fill() , .slice() , .splice() , .find() , .some() , .every() and Object.entries().
.map()- Transforming Arrays
What it does :
Creates a new array by applying a function to each element in the original array.
Example
const numbers = [1,2,3];
const newNum = numbers.map(num => num * 2);
console.log(nemNum); //[2,,4,6]
Real-World use (React)
Rendering a list in a React component.
const todos = ["eat", "sleep", "repeat"]
return (
<ul>
{todos.map((item =>(
<li key = {item}>{item>}</li> // wrapping each item under <li> tag.
))} // key is used to give unique identity to React.
</ul>
);
//Final Output
<ul>
<li>eat</li>
<li>sleep</li>
<li>repeat</li>
</ul>
Use Cases:-
Displaying a list of products from API in a component.
Converting API response data into UI-friendly format.
Creating drop down options from a config array.
Rendering dynamic routes/pages in Next.js
Mapping user roles to badges or access levels.
.filter()- Selective data
What it does:
Returns a new array with elements that match a given condition.
Example
const numbers = [1,2,4,6,9];
const newNum = numbers.filter(num => num % 2 === 0)
console.log(newNum) // [2,4,6]
Real World Use:
Filtering active user from list.
const users = [
{
name : "Harsh",
active : true
},
{
name : "Janvi",
active : false
}
]'
const activeUsers = users.filter(user => user.active);
console.log(activeUsers)
// output - [{name : "Harsh" , active : true}]
Use Cases:
Filtering active users, published posts or completed tasks
Showing results based on category.
Filtering out null or undefined values.
Displaying only verified accounts in dashboard.
.reduce()- One value from Many.
What it does :-
Reduces an array to a single value using an accumulator function.
Example
const num = [1,2,3,4];
const newNum = num.reduce((acc,num)=> acc + num, 0);
console.log(newNum); // 10
Real-World use :
Calculating cart total :
const cart =[
{item : "pen" , price : 10},
{item : "pencil" , price : 40}
];
const total = cart.reduce((sum , item) => sum + item.price , 0); //start value sum =0
console.log(total)
//output
50
Use cases:-
Calculating cart total amount or order summary.
Summing up likes , views or ratings.
Combining multiple form fields values into a single object.
Counting status(e.g. “pending” , “done”) appears in tasks.
Merging multiple datasets from API response into one.
.includes()- Quick check
What it does :-
Checks if a certain value exists in an array or string.
Example
const fruits = ["apple" , "banana" ];
console.log(fruits.includes("apple)) // true
Real-World use :
Role-Based access
const roles = ["admin" , "editor"]
if(roles.includes("admin")){
// grant admin access
}
Use Cases:-
Checking if a user has a specific role(admin ,editor, etc.)
Validating the input.
Verifying if a feature is enabled or not;
Avoiding duplicate entries before pushing new data in arrays.
.slice()- Non destructive cut
What it does :-
Returns a portion of an array without modifying the original one.
Example
const numbers = [1,2,3,4,5];
const sliced = numbers.slice(0,3);
console.log(sliced) // [1,2,3]
Real-World use :
Paginating data:
const pageData = allUsers.slice(0,10); // First 10 users.
Use Cases:-
Implementing pagination. (e.g., show first 10 users).
Limiting data shown in dashboard widgets.
Splitting arrays for multi-step forms.
.splice()- Destructive Edit
What it does :-
Changes the content of an array by removing or replacing elements.
Example:
const fruits = ["apple","banana" , "orange"]
fruits.splice(1,1); //remove banana
console.log(fruits); //["apple" , "mango"]
Real-World Use :
Removing an item from a list.
Replacing outdated data in memory before saving to DB.
Updating dropdown options dynamically.
.find() - First match finder
Returns the first element in an array that matches the condition.
const users [
{name : "Harsh" , active : true},
{name : "Shreya" , active : false},
{name : "Rahul", active : true}
]
const firstActive = users.find((user => user.active))
console.log(firstActive); // {name : "Harsh" , active : true}
Use Cases:-
Fetching the first available item from a filtered dataset (like the first active user, product in stock, etc.).
Getting a user by email or ID from an array
Finding the first available delivery slot
Getting the first unread notification or message
.some() - Check if any match exists.
Return true if any element in the array passes the test.
const numbers = [1, 3, 5, 6];
const hasEven = numbers.some(num => num % 2 === 0);
console.log(hasEven); // true
Checking if at least one user is online, if any product is discounted , etc.
const users = [
{ name: "Harsh", online: false },
{ name: "Janvi", online: true }
];
const isAnyoneOnline = users.some(user => user.online); // true
Use Cases :-
Detecting if any product in cart is out of stock
Checking if user has any unread message or alert
Checking if any required field is empty before form submit
.every() - All must match.
Returns true only if every item in the array passes the test.
const ages = [25, 28, 30];
const allAdults = ages.every(age => age >= 18);
console.log(allAdults); // true
Verifying conditions like: are all fields filled? Are all users verified? etc.
const forms = [
{ id: 1, filled: true },
{ id: 2, filled: true },
{ id: 3, filled: false }
];
const allFormsFilled = forms.every(form => form.filled); // false
Use Cases :-
Ensuring all fields are filled/valid before enabling submit
Checking if all users in a team are active
Validating if all steps in a process are completed
Making sure all required permissions are granted to proceed
Object.entries() - Convert Object to Array
Returns an array of a given object’s key-value pairs.
const person = { name: "Ali", age: 25 };
console.log(Object.entries(person));
// [["name", "Ali"], ["age", 25]]
Iterating over object properties.
Object.entries(person).map(([key, value]) => {
console.log(`${key}: ${value}`);
});
Use Cases:-
Looping over a settings/config object in UI
Converting form state object into key-value pairs before sending to API
Transforming validation error objects into UI error messages