Determine whether an array contains a value
⚡TLDR
To check if an array contains a value, utilize array.includes(value)
for an immediate boolean result or array.indexOf(value)
to obtain the position.
Test for uncertainty or NaN in arrays with some()
:
For browsers with no native includes()
, fall back to indexOf()
using a polyfill:
Dealing with array-like objects
For array-like objects, leverage Array.prototype.includes.call()
:
Writing efficient and maintainable code
- Avoid over-reliance on third-party libraries. Instead, use JavaScript's native methods.
- Use right-sized lodash imports if you choose lodash. Import only required functions.
- Use terse direct application syntax:
["Eat", "Sleep", "Code"].includes("Code")
and a friendly alien 👽 will visit you. - Validate your code regularly with online tools like CodePen or JSFiddle.
Advanced array checks and modifications
Multiple value checks
Performance implications
.includes()
can be a performance hog on large data sets. Use with caution and always benchmark when in doubt.
Code readability and maintenance
- Use expressive variable names and detailed code comments.
- Refer documentation for using techniques and methods aptly, enhancing code quality and readability.
More alternatives in search operations
- Use
Array.prototype.some()
if a matching condition is what you are looking for. - When you need more control, use
Array.prototype.filter()
to build your search.
Handling issues with cross-browser support
- Use polyfills for
.includes()
from Babel orcore-js
. - MDN provides a
includes()
polyfill to ensure your code works on older browsers. - For wider support, consider using lodash's
.includes()
.
Linked
Linked
Was this article helpful?