JavaScript undefined 속성이란?
JavaScript에서 undefined는 변수가 아직 값을 할당받지 못했거나, 선언만 된 상태임을 나타내는 특수한 값입니다. 즉, 어떤 변수에 값이 존재하지 않는다는 것을 확인할 때 유용하게 사용됩니다.
변수를 선언만 하고 초기화하지 않으면 해당 변수에는 자동으로 undefined가 할당됩니다. 이를 활용하면 코드 실행 중 변수의 정의 여부를 안전하게 검사할 수 있습니다.
다음은 JavaScript undefined 속성의 사용 예제 코드입니다.
예제 코드
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.sample {
font-size: 18px;
font-weight: 500;
color: red;
}
</style>
</head>
<body>
<h1>JavaScript undefined property</h1>
<div class="sample"></div>
<button class="Btn">CLICK HERE</button>
<h3>
CLICK the above button to know if variable age has been defined or not
</h3>
<script>
let sampleEle = document.querySelector(".sample");
let age;
document.querySelector(".Btn").addEventListener("click", () => {
if (age === undefined) {
sampleEle.innerHTML ="The variable age has not been defined yet or no value is given to it";
} else
sampleEle.innerHTML ="The variable age is defined and its value = " + age;
});
</script>
</body>
</html>코드 설명
let age;– 변수 age를 선언하지만 값을 할당하지 않으므로 현재undefined상태입니다.- 버튼 클릭 시
age === undefined조건문을 통해 변수에 값이 있는지 검사합니다. - 값이 없다면 "아직 정의되지 않았다"는 메시지를, 값이 있다면 해당 값을 화면에 출력합니다.
실행 결과
페이지가 처음 로드된 화면은 다음과 같습니다.

'CLICK HERE' 버튼을 클릭하면 변수 age가 아직 정의되지 않았다는 결과가 표시됩니다.

추가 팁: undefined와 null의 차이
undefined는 '값이 할당되지 않은 상태'를 의미하는 반면, null은 개발자가 의도적으로 '값이 비어 있음'을 지정한 것입니다. 또한 typeof undefined는 문자열 "undefined"를 반환하므로, 타입 검사에도 활용할 수 있습니다.