Why does my recursive object search match the string "44" to the number 44?
Asked by
MellowCedar27
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.
Answers
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.
Reply to this answer
`===` does not convert types. `44 === "44"` is false, while `44 == "44"` would perform type coercion and return true. If youโre seeing true, look for another comparison in the code being executed or make sure the test is running the current file. Also add a null guard before calling `Object.values`, since `typeof null` misleadingly returns `"object"`.
Reply to this answer
Add your answer
Answers are reviewed before publication.
MellowCedar27: 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.