0

My task is to create a function that checks if a specific property exists in object. I don't understand why the second log returns false when 'b' obviously exists in numbers object. Would be very happy if someone can explain the solution to me :)

const existInObject = (obj = {}, prop) => {
    for (const key in obj) {
      if(key === prop) {
        return true;
      } else {
        return false;
      }
    }
};

const numbers = { 
    a: 5,
    b: 4,
}

const result1 = existInObject(numbers, "a");
const result2 = existInObject(numbers, "b");

console.log(result1, result2); // true, false
gopetoamg
  • 19
  • 5
  • Doesn't the built-in `hasOwnProperty()` method do what you want? – Barmar Mar 30 '21 at 08:56
  • 2
    You're returning on the first iteration, so you're only checking if the first property matches, not if any object matches. – Barmar Mar 30 '21 at 08:57
  • `const existInObject = (obj = {}, prop) => obj.hasOwnProperty(prop);` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty – Paul Adam Mar 30 '21 at 09:03

1 Answers1

0

The reason it doesn't work is because what Barmar said, "You're returning on the first iteration, so you're only checking if the first property matches, not if any object matches". You have to go through all the keys to see if there's a match and return the result after that.

const existInObject = (obj = {}, prop) => {
    var result = false;
    for (const key in obj) {
      if(key === prop) {
        result = true;
      }
    }
    return result
};

const numbers = { 
    a: 5,
    b: 4,
}

const result1 = existInObject(numbers, "a");
const result2 = existInObject(numbers, "b");
const result3 = existInObject(numbers, "c");

console.log(result1, result2, result3); // true, true, false
Rifat Bin Reza
  • 2,601
  • 2
  • 14
  • 29