.Has Method - Recreating the Lodash library

This is pertaining to the has method in Recreating the Lodash library exercise.
Steps 19 - 22
https://www.codecademy.com/paths/web-development/tracks/web-dev-js-arrays-loops-objects/modules/pjs-javascript-capstone/projects/lodash

Here is my code -
has(obj, key){
if(obj[key] === undefined){
return false;
}else{
return true;
}
}
Initially the above code failed the validation because I had the conditional as
if(obj.key === undefined)
When I changed it to if(obj[key] === undefined), the validation passed.

Can somebody please tell me why the .notation (obj.key) will not work?

Regards
Gopal

the dot notation/property notation only works when we code the property:

obj.prop

the moment the property/key is a string, contains special character, the associative array notation (square brackets) has to be used:

obj.'prop'` // doesn't work
obj['prop'] // works

given the parameter (key) is a string value, you have to use the square brackets

bonus: a condition/comparison results in a Boolean value (a comparison is either true or false). so you can shorten your code.

Thank you.
That makes sense.
How is this?
has(obj, key){
if(obj[key] === undefined){
return false;
}
}

that looks good, but hadn’t you already figured that out? I though your question was a of the clarifing kind

Yes, I did figure that out.
In order to get used to the coding syntax, I am not going for the concise approach.
But now that I think, I should look for avenues to shorten the code as well.

Thank you again for your prompt response.

1 Like