I’m working through the lodash challenge.
My solution to the has() method passes. Here it is:
has(myObject, myKey) {
if (myObject[myKey]) {
return true;
}
return false;
The suggested solution says we should use a variable ‘hasValue’ in the method, and assign it a true/false value after testing if the object has a key.
My question is, is this necessary? It seems long-winded. I’m wondering if I’m missing something.
Thanks for looking!
It is indeed unnecessary. But you could also rewrite your code as follows:
function has(object, key) {
return object[key]
}
// or even, since this is a one-liner
const has = (object, key) => object[key]
Of course, this makes the challenge look trivial, and it is. Technically, the actual Lodash has method is more robust and can check for nested objects. Like for example, our implementations would not work with this, but Lodash’s would:
const object = { a: { b } }
_.has(object, b) // returns true
has(object, b) // returns false
1 Like
Many thanks for the enlightening input. I particularly like the brevity of your one-liner!