I'm implementing a recursive contains function that searches through all values in a nested JavaScript object. The object contains a numeric value, magicNumber: 44, while the test calls contains(object, "44") and expects false because the search value is a string. I'm using the strict equality operator (===), so I don't understand why the test appears to return true. The object also contains nested objects, an array, NaN, and a null value.
1 Answer
There shouldn’t be any implicit conversion here. With `value === find`, the number `44` and the string `"44"` are different values, so that comparison is false. The code as posted has a couple of other issues, though: `meaningOfLifeArray` must be defined, and `typeof null` is `"object"`. That means the recursive call will eventually try `Object.values(null)`, which throws an error. Check for null before recursing, for example: `if (value !== null && typeof value === "object" && contains(value, find)) return true;`. After fixing those issues, searching for `"44"` should return false.

The array is defined as `[42]` in the actual exercise, so I’ll check the null case and verify the exact code being run. I may have been testing a slightly different version than the one I posted.