Syntax, Parameter and Return Value
Syntax:
_.includes(collection, value, [fromIndex=0])
Parameters:
-
collection (Array|Object|string): The collection to search.
-
value: The value to search for.
- [fromIndex=0] (number): The index to start the search from.
Return Value:
(boolean) - Returns true if value is found, else false.
Examples
Checking for a Number in an Array:
JavaScript
var _ = require('lodash');
var numbers = [1, 2, 3, 4, 5];
var includesTwo = _.includes(numbers, 2);
console.log(includesTwo);

You can also try this code with Online Javascript Compiler
Run Code
Output:
true
Demonstrates searching for a number in an array.
Searching for a Property Value in an Object:
JavaScript
var object = { 'a': 1, 'b': 2, 'c': 3 };
var includesThree = _.includes(object, 3);
console.log(includesThree);

You can also try this code with Online Javascript Compiler
Run Code
Output:
true
Shows how to search for a value within an object's properties.
Finding a Substring in a String:
JavaScript
var string = "hello world";
var includesHello = _.includes(string, "hello");
console.log(includesHello);

You can also try this code with Online Javascript Compiler
Run Code
Output:
true
An example of checking for a substring within a string.
Using fromIndex for Array Search:
JavaScript
var includesTwoAfterIndexTwo = _.includes(numbers, 2, 2);
console.log(includesTwoAfterIndexTwo);

You can also try this code with Online Javascript Compiler
Run Code
Output:
false
Demonstrates searching for an element in an array starting from a specific index.
Frequently Asked Questions
How does _.includes() differ from native JavaScript includes?
Lodash's _.includes() works across different types of collections, including arrays, objects, and strings, unlike the native includes which is limited to arrays and strings.
Can _.includes() be used to find partial objects in an array?
_.includes() checks for primitive values and will not match partial objects; it compares object references for equality.
Is _.includes() case-sensitive when searching in strings?
Yes, when searching within strings, _.includes() is case-sensitive and will only find exact matches.
Conclusion
Lodash's _.includes() method is a versatile and efficient way to check for the presence of a value within various types of collections. It simplifies the process of searching and validating data, enhancing the functionality and readability of JavaScript code.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc.
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.