-1

I would like to create a JS function that takes two arguments: an Object and a property. If the object has the given property, then the function should remove it from the object, and return true.

This is as far as I've got, but it keeps returning false on test cases. I believe because the 'obj.prop' part is not catching properly - but not sure why.

Any help would be much appreciated!

function removeProperty(obj, prop) {

  if ( obj.prop ) {

     delete obj.prop;
     return true;    

  }  else {

     return false;
  }
}
T132
  • 21
  • 2
  • Use `obj[prop]` instead of `obj.prop` – Satpal Jul 28 '17 at 10:00
  • 1
    "If the object has the given property" you are not checking this. You are checking that object or any object up the prototype chain has the property that is truthy. There are a lot of edge cases your code would fail. – Yury Tarabanko Jul 28 '17 at 10:03
  • It seems odd that your function would need to `return false` if the property doesn't exists; checking for existence and removing a property seems like two different things. A simple `delete obj[prop]`, without any function, should do just fine. After that the property won't exist, regardless of whether it already did or didn't exist. – deceze Jul 28 '17 at 10:05

2 Answers2

1

Change like this .You are passing the variable not direct name of the property

 function removeProperty(obj, prop) {
  if (obj[prop]) {
    delete obj[prop];
    return true;
  } else {
    return false;
  }
}
prasanth
  • 22,145
  • 4
  • 29
  • 53
1

You are using the dot syntax to get the property --> obj.prop

Using it this way you are actually asking the property named prop of your object

{
    prop: 'something'
}

You should use the brackets notation --> obj[prop]

function removeProperty(obj, prop) {
  if ( obj[prop] ) {
     delete obj[prop];
     return true;    
  }  else {
     return false;
  }
}
Weedoze
  • 13,683
  • 1
  • 33
  • 63