JavaScript Snippet

Value-In-Array and Value-In-Object Checks

Difficulty: Easy

"Is X in this array?" and "is X anywhere in this object?" sound like the same question but call for different tools. Arrays have `includes` (which handles `NaN`), `indexOf` (which does not), and `Set.has` for hot paths. Objects need `Object.values` for a flat scan and a recursive walk for nested structures. This snippet covers both, with the gotchas that bite: `NaN`, hot-path scans, and shared object identity.

Code Snippets
/

Value-In-Array and Value-In-Object Checks

Value-In-Array and Value-In-Object Checks

"Is X in this array?" and "is X anywhere in this object?" sound like the same question but call for different tools. Arrays have `includes` (which handles `NaN`), `indexOf` (which does not), and `Set.has` for hot paths. Objects need `Object.values` for a flat scan and a recursive walk for nested structures. This snippet covers both, with the gotchas that bite: `NaN`, hot-path scans, and shared object identity.

JavaScript
Easy
2 snippets
arrays
references
conditionals

605 views

13

includes is the right default for primitives: it handles NaN correctly and reads as a yes/no question. indexOf !== -1 is the older idiom and fails the NaN case because it uses strict equality. For a hot loop or membership check inside a render path, build a Set once with new Set(values) and call .has(x) per lookup; that turns repeated linear scans into average O(1). The biggest gotcha is OBJECT membership: [{id:1}].includes({id:1}) is false because the two object literals are distinct references. For "find by field value", reach for .some(predicate) or .find(predicate) instead.