전역 undefined 속성은 undefined 원시 값을 나타내며, JavaScript의 원시 자료형 중 하나입니다.
Property attributes of undefined |
|
|---|---|
| Writable | no |
| Enumerable | no |
| Configurable | no |
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
설명
undefined는 전역 객체의 속성입니다. 즉, 전역 스코프에서의 변수입니다. undefined의 초기 값은 undefined 원시 값입니다.
최신 브라우저에서 undefined는 ECMAScript 5 명세에 따라 설정 불가, 쓰기 불가한 속성입니다. 그렇지 않더라도 덮어쓰는건 피하는게 좋습니다.
값을 할당하지 않은 변수는 undefined 자료형입니다. 또한 메서드와 선언도 평가할 변수가 값을 할당받지 않은 경우에 undefined를 반환합니다. 함수는 값을 명시적으로 반환하지 않으면 undefined를 반환합니다.
undefined는 예약어가 아니기 때문에 전역 범위 외에서 식별자(변수 이름)로 사용할 수 있습니다. 그러나 유지보수와 디버깅 시 어려움을 낳을 수 있으므로 반드시 피해야 합니다.
// 하면 안되는 일의 예시
// logs "foo string"
(function() { var undefined = 'foo'; console.log(undefined, typeof undefined); })();
// logs "foo string"
(function(undefined) { console.log(undefined, typeof undefined); })('foo');
예제
일치 연산과 undefined
undefined와 일치, 불일치 연산자를 사용해 변수에 값이 할당됐는지 판별할 수 있습니다. 다음 예제에서 변수 x는 초기화되지 않았으므로 if문은 true로 평가됩니다.
var x;
if (x === undefined) {
// 이 문이 실행됨
}
else {
// 이 문이 실행되지 않음
}
참고: 일반적인 동등 연산자가 아니라 일치 연산자를 사용해야 합니다. 동등 연산자일 때 x == undefined는 x가 null일 때도 참이기 때문입니다. 즉 null은 undefined와 동등하지만, 일치하지는 않습니다. 자세한 내용은 비교 연산자 문서를 확인하세요.
typeof 연산자와 undefined
위의 예제 대신 typeof를 사용할 수도 있습니다.
var x;
if (typeof x === 'undefined') {
// 이 문이 실행됨
}
typeof를 사용하는 이유 중 하나는 선언하지 않은 변수를 사용해도 오류를 던지지 않기 때문입니다.
// x를 선언한 적 없음
if (typeof x === 'undefined') { // 오류 없이 true로 평가
// 이 문이 실행됨
}
if(x === undefined) { // ReferenceError
}
그러나 이런 방식은 피해야 합니다. JavaScript는 정적 스코프 언어이므로, 변수의 선언 여부는 현재 문맥의 코드를 읽어 알 수 있습니다. 유일한 예외는 전역 범위인데, 전역 범위는 전역 객체로 묶여 있으므로 변수의 존재 여부는 전역 객체의 속성 존재 여부(in 연산자)로 판별할 수 있습니다.
void 연산자와 undefined
void 연산자를 제 3의 대안으로 사용할 수 있습니다.
var x;
if (x === void 0) {
// 이 문이 실행됨
}
// y를 선언한 적 없음
if (y === void 0) {
// Uncaught Reference Error: y is not defined
}
명세
| 명세 | 상태 | 설명 |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'undefined' in that specification. |
Standard | |
| ECMAScript 5.1 (ECMA-262) The definition of 'undefined' in that specification. |
Standard | |
| ECMAScript 1st Edition (ECMA-262) The definition of 'undefined' in that specification. |
Standard | 최초 정의. JavaScript 1.3 에서 시행됨. |
브라우저 호환성
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
undefined | Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support 5.5 | Opera Full support Yes | Safari Full support Yes | WebView Android Full support 1 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support 1.0 | nodejs Full support Yes |
Legend
- Full support
- Full support