Extremely Useful Lodash Methods For JavaScript Developers

Full Stack Developer | Freelancer | JavaScript | React | Nodejs.
Loves sharing knowledge through technical articles.
Dev.to: https://dev.to/myogeshchavan97
https://linktr.ee/myogeshchavan97
Search for a command to run...

Full Stack Developer | Freelancer | JavaScript | React | Nodejs.
Loves sharing knowledge through technical articles.
Dev.to: https://dev.to/myogeshchavan97
https://linktr.ee/myogeshchavan97
No comments yet. Be the first to comment.
In this tutorial, you will build a Task Management App using Next.js 16 and Prisma 7 from scratch. By creating this app, you will learn: How to set up Prisma 7 with the new Rust-free architecture How to configure a database with Prisma's driver ada...

If you're a React/Next.js developer who diligently updated your packages last week after the critical React2Shell vulnerability (CVE-2025-55182), I have some frustrating news: you need to update again. Security researchers, while probing the patches ...

Is your React app dragging its feet, but you can’t pinpoint the cause? You might think you’re following the best practices, but some common development patterns are actually degrading your app’s performance behind the scenes. In this article, we’ll u...

How to Use Separate SSH Keys for Company and Personal GitHub Accounts Managing multiple GitHub accounts is a common challenge for developers who juggle both personal and professional projects. It becomes even more complex when you want to use differe...

Have you ever built a React app only to realize that users from different countries can't use it effectively because it only supports English? In this tutorial, you'll learn how to build truly global React application using internationalization (i18n...

According to the State of Javascript 2020 Survey results, Lodash is the second most widely used utility library in the world as it provides a lot of methods that make coding easy and fast.
In this article we will see, some of the most useful methods provided by lodash which makes coding easy.
So let's get started.
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>
npm install --save lodash
Let’s explore some of the most useful methods provided by lodash.
The isEqual method performs a deep comparison between two values.
Syntax:
_.isEqual(value, other)
Take a look at the below code:
const obj1 = {
name: 'Ram',
age: 20,
location: {
city: 'NY',
state: 'NY'
}
};
const obj2 = {
name: 'Ram',
age: 20,
location: {
city: 'NY',
state: 'NY'
}
};
console.log(_.isEqual(obj1, obj2)); // true
Here's a Code Pen Demo.
If you are showing user profile data pre-filled when the user logs in to the system and if you are making a web service API call to save the changed user details when the user clicks on the save button, you can easily check if the user has changed something or not before making API call using lodash’s isEqual method.
isEqual is much faster than other alternatives when comparing two deeply nested objects. The other ways of comparing two objects are manually comparing each property or using the JSON.stringify method.
The isEmpty method checks if value is an empty object, collection, map, or set.
Syntax:
_.isEmpty(value)
Take a look at the below code:
const obj1 = { name: 'David' };
console.log(_.isEmpty(obj1)); // false
const obj2 = {};
console.log(_.isEmpty(obj2)); // true
const array1 = [];
console.log( _.isEmpty(array1)); // true
const array2 = [2, 3];
console.log(_.isEmpty(array2)); // false
const nullValue = null;
console.log(_.isEmpty(nullValue)); // true
const undefinedValue = undefined;
console.log(_.isEmpty(undefinedValue)); // true
Here's a Code Pen Demo.
As you can see the isEmpty method quickly allows testing for an empty value. Instead of using Object.keys(obj1).length === 0 to check for an empty object, isEmpty makes it easy to perform the check.
The get method gets the value at the path of an object. If the resolved value is undefined, the defaultValue is returned in its place.
Syntax:
_.get(object, path, [defaultValue])
Take a look at the below code:
const user = {
"gender": "male",
"name": {
"title": "mr",
"first": "brad",
"last": "gibson"
},
"location": {
"street": "9278 new road",
"city": "kilcoole",
"state": "waterford",
"postcode": "93027",
"coordinates": {
"latitude": "20.9267",
"longitude": "-7.9310"
},
"timezone": {
"offset": "-3:30",
"description": "Newfoundland"
}
}
};
console.log(_.get(user, 'location.timezone', {})); // {'offset':'-3:30','description':'Newfoundland'}
console.log(_.get(user, 'name.middlename', '')); // ''
Here's a Code Pen Demo.
The great thing about lodash’s get method is that, if the location property does not exist in the user object, directly accessing it as user.location.timezone will throw an error but If lodash’s get method is used, it will not throw an error but will return the default value.
const user = {
"gender": "male",
"name": {
"title": "mr",
"first": "brad",
"last": "gibson"
}
};
// This will work and will return the default value specified
console.log('timezone:',_.get(user, 'user.location.timezone', ''));
// Error: Cannot read property 'timezone' of undefined
console.log('timezone:',user.location.timezone);
The sortBy method creates an array of elements, sorted in ascending order by the results of running each element in a collection through each iteratee.
Syntax:
_.sortBy(collection, [iteratees=[_.identity]])
Take a look at the below code:
const users = [
{ 'user': 'fred', 'age': 48 },
{ 'user': 'barney', 'age': 36 },
{ 'user': 'fred', 'age': 40 },
{ 'user': 'barney', 'age': 34 }
];
//sort users by age
console.log(_.sortBy(users, [function(user) { return user.age }]));
// output: [{'user':'barney','age':34},{'user':'barney','age':36},{'user':'fred','age':40},{'user':'fred','age':48}]
Here's a Code Pen Demo.
The orderBy method is similar to sortBy but it allows us to specify the descending or ascending sort order. For descending sort, we specify desc and for ascending we specify asc.
Syntax:
_.orderBy(collection, [iteratees=[_.identity]], [orders])
Take a look at the below code:
const users = [
{ 'user': 'fred', 'age': 48 },
{ 'user': 'barney', 'age': 36 },
{ 'user': 'fred', 'age': 40 },
{ 'user': 'barney', 'age': 34 }
];
// sort by user in descending order
console.log(_.orderBy(users, ['user'], ['desc']));
// sort by user in ascending order and age by descending order
console.log(_.orderBy(users, ['user', 'age'], ['asc', 'desc']));
Here's a Code Pen Demo.
The union method returns the unique values from all the arrays passed.
Syntax:
_.union([arrays])
Take a look at below code:
console.log(_.union([1], [1, 2, 3], [-1, 0, 4], [2, 2, 3])); // [1, 2, 3, -1, 0, 4]
Here's a Code Pen Demo.
The cloneDeep method returns a clone/copy of an object recursively. This is very useful if you don’t want to change the original object but create a copy of the object to add extra properties to it.
Syntax:
_.cloneDeep(value)
Take a look at the below code:
const obj = {
name: {
title: "Ms",
first: "Hannah",
last: "Ennis"
},
location: {
city: "Flatrock",
state: "British Columbia",
country: "Canada",
postcode: "P1X 7D3",
coordinates: {
latitude: "-62.3907",
longitude: "37.8088"
},
timezone: {
offset: "+5:30",
description: "Bombay, Calcutta, Madras, New Delhi"
}
}
};
const clone = _.cloneDeep(obj);
console.log(obj.name === clone.name); // false
console.log(clone === obj); // false
Here's a Code Pen Demo.
As you can see from the above comparison of clone.name and obj.name, _.cloneDeep creates totally different object which is a copy/clone.
The debounce method is the most useful lodash method and it allows us to call a function after some milliseconds have passed.
Syntax:
_.debounce(func, [wait=0], [options={}])
Note: the debounce method returns a function that we invoke to make subsequent calls.
This is a very useful method that allows us to minimize the number of API calls to the server.
Let’s build a search functionality where a user types some information as input, and we will make an API call to the server to get the result based on the input.
In the above without debouncing example, you can see that on every keystroke, we are making an API call.
So we are unnecessarily increasing the server API calls. If the server is taking more time to return the data, you might see the previous result even when you are expecting new results based on your input value.
To fix this we can use debouncing where we only make an API request after 300 milliseconds once a user has stopped typing which is more beneficial. It will save from unnecessary requests and will also save from previous API call result being displayed for a short amount of time.
In the above code, the debounce method returns a function which we’re storing in debFunction variable.
const debFunction = _.debounce(onSearchText, 300);
Then for every key change event, we’re calling the function stored in debFunction variable after 300 milliseconds once the user has stopped typing. Calling debFunction, internally, calls the onSearchText function where we're actually making an API call.
Want to know how to use debouncing to improve the performance of your search in React application? Check out my this article.
You can explore all other methods of lodash HERE.
Check out my recently published Mastering Redux course.
In this course, you will build 3 apps along with food ordering app and you'll learn:
and then finally we'll build a complete food ordering app from scratch with stripe integration for accepting payments and deploy it to the production.
Want to stay up to date with regular content regarding JavaScript, React, Node.js? Follow me on LinkedIn.