Skip to content
Search

JavaScript:undefined

lastmod 2022-04-05created 2022-04-052 edits

Everything related to undefined in JavaScript.

Description

undefined is a property of the global object. That is, it is a variable in the global scope. The initial value of undefined is the primitive value undefined.

In modern browsers, undefined is a non-configurable, non-writable property, per the ECMAScript 5 specification. Even when this is not the case, it is best to avoid overwriting it.

A variable that has not been assigned a value is of type undefined. A method or statement also returns undefined if the variable being evaluated does not have an assigned value. A function returns undefined if a value was not explicitly returned.

WARNING

Because undefined is not a reserved word, it can be used as an identifier (variable name) outside the global scope. However, this must be avoided, since it can make maintenance and debugging difficult.

Strict equality and undefined

You can use undefined with the strict equality and inequality operators to determine whether a variable has a value. In the following example, the variable x is not initialized, so the if statement evaluates to true.

var x;
if (x === undefined) {
   // 이 문이 실행됨
} else {
   // 이 문이 실행되지 않음
}

INFORMATION

Content

See the comparison operators (en-US) page for details.

The typeof operator and undefined

Alternatively, typeof can be used instead of the example above.

var x;
if (typeof x === 'undefined') {
   // 이 문이 실행됨
}

One reason to use typeof is that it does not throw an error even if the variable has not been declared.

// x를 선언한 적 없음
if (typeof x === 'undefined') { // 오류 없이 true로 평가
  // 이 문이 실행됨
}

if (x === undefined) { // ReferenceError
  // ...
}

However, there is another approach. Since JavaScript is a statically scoped language, whether a variable is declared can be determined by reading the code in the current context.

The global scope is bound to the global object, so whether a variable exists in the global context can be checked by applying the in operator to the global object. That is,

if ('x' in window) {
  //  x가 전역으로 정의된 경우 이 문이 실행됨
}

The void operator and undefined

The void operator can be used as a third alternative.

var x;
if (x === void 0) {
   // 이 문이 실행됨
}

// y를 선언한 적 없음
if (y === void 0) {
   // Uncaught Reference Error: y is not defined
}

See also

Favorite site

author Zer0 sitemap