📦

Has Property

Has Property - Explanation

쉬움 객체 O(1) O(1)

Problem Summary

Write a function that checks if an object has a specific property.

Go to Problem →

Detailed Explanation

이 문제는 **in 연산자**를 사용하여 객체에 속성이 존재하는지 확인하는 방법을 학습합니다. ## 핵심 개념: 속성 존재 확인 객체에 특정 속성이 있는지 확인하는 방법은 여러 가지가 있습니다. ### 방법 1: in 연산자 ```javascript key in obj ``` - 상속된 속성도 확인 - 가장 간단한 문법 ### 방법 2: hasOwnProperty ```javascript obj.hasOwnProperty(key) ``` - 자체 속성만 확인 (상속 제외) ### 방법 3: undefined 비교 (권장하지 않음) ```javascript obj[key] !== undefined ``` - 값이 undefined인 속성을 감지하지 못함 ### 비교 예시 ```javascript const obj = {a: 1}; 'a' in obj // true 'b' in obj // false 'toString' in obj // true (상속됨) obj.hasOwnProperty('toString') // false ``` ### 실무 팁 Object.hasOwn(obj, key)는 ES2022에서 도입된 더 안전한 방법입니다.

Solution Code

solution.js
function hasProperty(obj, key) {
  return key in obj;
}

Key Concepts from This Problem

1. in 연산자
2. hasOwnProperty
3. 속성 확인
4. 상속 속성

Common Mistakes

✗ in은 상속된 속성도 true를 반환합니다
✗ undefined 값과 존재하지 않는 속성을 구분해야 합니다
✗ hasOwnProperty는 덮어쓰여질 수 있으므로 Object.hasOwn이 더 안전합니다

Hints

Hint 1: in 연산자 또는 hasOwnProperty를 사용하세요.

Complexity Analysis

Time Complexity

O(1)

Constant time regardless of input size

Space Complexity

O(1)

Uses almost no additional memory

Related Tags

#객체 #in #검사