Why can' I use this code?

Tell us what’s happening:

Your code so far


function checkObj(obj, checkProp) {
// Only change code below this line
if(obj.hasOwnProperty(checkProp) == true){
  return obj[checkProp];
}
else{
  return "Not Found";
}
// Only change code above this line
}

Your browser information:

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

Challenge: Testing Objects for Properties

Link to the challenge:

Why can’t I do this ?

function checkObj(obj, checkProp) {

  // Only change code below this line

  if(obj.hasOwnProperty(checkProp) == true){

    return obj.checkProp;
  }
  else{
    return "Not Found";
  }
  // Only change code above this line
}

you may want to review the challenge Accessing Object Properties with Variables

I mean why can’t I use this? :

return obj.checkProp;

Between the brackets [ ] checkProp gets evaluated. This is why. When is evaluated whatever was as value passed to your function call gets extracted.

Is a function parameter and value can be “whatever” if string is expected.

But you may not have the property named as the function parameter on that object inside the function.

You may have on the object the property named as the value extracted out of checkProp though.

Basically, obj.checkProp is not same as obj[checkProp] in your case.

1 Like

oh wow ! I realised :slight_smile: thank you.

1 Like

As a matter of fact, I use this pattern a lot when working with React.

//Class method syntax

  toggle(type) {
    this.setState( state => ({[type] : !state[type]}) );
  }

//Later you can call it on whatever piece of the state you like

  this.toggle('modalCustomer')
  this.toggle('modalBooking')
//etc ....

...

In my opinion is a very powerful way of abstraction. Some may consider it a bit too implicit, but that is out of context.