자바스크립트 빈값, null, undefined 체크하기

//typeof가 타입을 검사해줍니다.
if (typeof undefinedValue === 'undefined' ) {
  console.log("1. undefined");
} // => 변수가 존재하지 않은 경우 채크 가능

//에러
//if (!undefinedValue) {
//  console.log("2. undefined");
//}

var emptyValue = '';

if (emptyValue === '') {
  console.log('3. empty');
}

// 빈 값은 기본적으로 false를 리턴합니다.
if (!emptyValue) {
  console.log('4. emptyValue');
}


var nullValue = null;

if (nullValue === null) {
  console.log("5. null");
}

//null 값은 false를 리턴합니다.
if (!nullValue) {
  console.log('6. nullValue');
}

//함수의 존재여부를 판단합니다.
if( typeof(function_1) == 'function' ) {
     console.log('7. there are no function');
}



//결과
1. undefined
3. empty
4. emptyValue
5. null
6. nullValue
7. there are no function

 

 

아래와 같이 메소드로 만들어 놓으면 재사용 가능

function isNotEmpty(val) {
	if (val !== null && val !== '' && typeof val !== 'undefined') {
		return true;
	}
	return false;
}

function isEmpty(val) {
	return !isNotEmpty(val);
}