[JavaScript] 배열과 객체 빈 값 비교하기 - null, undefined ...

728x90

Falsy 값 체크

JavaScript에서 빈 값을 검사할 때 가장 간단한 방법은 Falsy 값을 확인하는 것이다. JavaScript의 Falsy 값에는 null, undefined, "" (빈 문자열), 0, NaN, false가 있다. 이러한 값들은 조건문에서 false로 인식되므로 if (!value) 문을 통해 빈 값 여부를 검사할 수 있다.

 

function isEmpty(value) {
  return !value;
}

// 사용 예시
console.log(isEmpty(null));        // true
console.log(isEmpty(undefined));   // true
console.log(isEmpty(""));          // true
console.log(isEmpty(0));           // true
console.log(isEmpty(NaN));         // true
console.log(isEmpty(false));       // true
console.log(isEmpty("hello"));     // false

 

객체의 빈 값 체크

객체가 비어 있는지 확인하는 경우에는 Object.keys()를 활용할 수 있다. Object.keys()는 객체의 속성 이름들을 배열로 반환하기 때문에 배열의 길이가 0이라면 빈 객체로 판단할 수 있다.

function isObjectEmpty(obj) {
  return Object.keys(obj).length === 0;
}

// 사용 예시
console.log(isObjectEmpty({}));               // true
console.log(isObjectEmpty({ name: "John" })); // false

 

배열의 빈 값 체크

배열은 길이(length)를 확인하여 빈 배열인지 판단할 수 있다.

function isArrayEmpty(arr) {
  return Array.isArray(arr) && arr.length === 0;
}

// 사용 예시
console.log(isArrayEmpty([]));         // true
console.log(isArrayEmpty([1, 2, 3]));  // false

 

문자열의 빈 값 체크

문자열의 경우에는 길이(length)를 확인하거나 앞에서 설명한 Falsy 값을 이용하여 간단하게 체크할 수 있다.

function isStringEmpty(str) {
  return typeof str === "string" && str.trim().length === 0;
}

// 사용 예시
console.log(isStringEmpty(""));        // true
console.log(isStringEmpty("   "));     // true (공백만 있는 문자열)
console.log(isStringEmpty("hello"));   // false

 

728x90