Reputation: 21
I'm working through TestDome.com and ran into this question.
Implement the removeProperty function which takes an object and property name, and does the following:
If the object obj has a property prop, the function removes the property from the object and returns true; in all other cases it returns false.
My solution was this:
function removeProperty(obj, prop) {
if (obj[prop]) {
delete obj[prop];
return true;
} else {
return false;
}
}
The test says that this doesn't work and their solution is:
function removeProperty(obj, prop) {
if (prop in obj) {
delete obj[prop];
return true;
} else {
return false;
}
}
For the life of me I can't figure out why my solution is wrong.
Edit: further examples.
const a = { b: 'c'};
if(a['b']) {console.log(true);} //true
if('b' in a) {console.log(true);} //true
Upvotes: 0
Views: 161
Reputation: 36630
The difference is the following:
obj = {
prop: 1
};
// retrieves the property from the object
console.log(obj['prop']); // 1
// checks if prop is in obj object
console.log('prop' in obj); // true
In the case of an if statement, both will evaluate to true. However, if the value retrieved from obj['prop']
is coerced to false
the if
block would not run. For example:
obj = {
prop: 0
};
// 0 convert to false so
if (obj['prop']) {
console.log('executed 1');
}
// prop is a property of obj so
// 'prop' in obj will evaluate to true
if ('prop' in obj) {
console.log('executed 2');
}
Upvotes: 2
Reputation: 3830
let's say you have an object
const a = {apple: 0}
In this case, a['apple']
would be falsy, where as "apple" in a
would be truthy.
Therefore, if you want to delete some key, just delete the key directly. I believe you do not even need to check for it before deleting it.
Upvotes: 0