Basic JavaScript - Testing Objects for Properties

Every so often I go back over the old tests to see if I can do them using what I’ve learnt so far.

I tend to read the explanations after trying it for myself even if it passes.

This is one that passed, but I’m not completely sure why?
And fear it may cause unintended behaviour if I use it to check for a property in another project.

function checkObj(obj, checkProp) {
  // Only change code below this line

  if (obj[checkProp]) {
    return obj[checkProp];
  } else {
    return "Not Found"
  // Only change code above this line

I’m aware of the correct way to pass using .hasOwnProperty() but do not wish to put the correct answer directly into this post.

What I don’t really understand is what’s happening in the example to allow it to pass.

I’ve tried breaking it down line by line but am not sure if I have misconceptions of what is happening or if this is just another method of doing the same thing

This is what I think is happening:

if (obj[checkProp]) { == if object property has a value, the statement is true?
return obj[checkProp]; == declare an undefined property within the object.

return "Not Found" == if the object property doesn’t exist it has no value, the statement is false, this code is run?

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/ Safari/537.36 Edg/114.0.1823.43

Challenge: Basic JavaScript - Testing Objects for Properties

Link to the challenge:


Almost. This checks if the value associated with obj[check prop] is Truthy

No? The obj is not being changed in any way. This is a return statement that describes what value to return

Almost. This part runs if the property is Falsy, and undefined values are Falsy

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.