MDN wants to learn about developers like you: https://qsurvey.mozilla.com/s3/d6d7ff2e2f9c

현재 번역은 완벽하지 않습니다. 한국어로 문서 번역에 동참해주세요.

delete operator는 오브젝트의 속성을 삭제한다.

문법 

delete expression 

expression은 속성 레퍼런스여야만 한다. e.g.:

delete object.property
delete object['property']

파라미터

object
오브젝트의 이름. 또는 오브젝트 표현식.
property
삭제하고자 하는 속성 

리턴 값

non-configurable 속성(역: 속성을 제거할 수 있는지)인 경우를 제외하고는 모든 경우에 관하여 true이다. non-configurable 속성인 경우는 non-strict에서 false를 반환한다.

예외

non-configurable속성인 경우에  strict mode에서 Global_objects/SyntaxError를 낸다.

설명

일반적으로 생각하고 있는것과는 다르게 delete 는 메모리 해제에 관하여 직접적으로 어떠한 작업도 하지 않습니다. 메모리 관리는 breaking references를 통하여 간접적으로 일어납니다. 자세한 걸 알고 싶다면 memory management 를 보세요.

delete연산자는 오브젝트로 부터 해당 프로퍼티를 삭제합니다. 삭제를 하면 true를 반환, 아니면 false를 반환합니다. 그렇지만 아래 경우를 고려해야만 합니다. 

  • 만약 존재하지 않는 속성을 삭제하려고 하면 delete는 어떠한 작업도 없이 true를 반환합니다.
  • 오브젝트의 프로토타입 체인에 같은 이름의 속성이 있다면, 삭제 후에,  오브젝트의 프로토타입체인을 통해 프로퍼티를 사용 할 수 있습니다. (즉, delete는 오직 자신의 프로퍼티만 삭제 합니다.
  • var로 선언된 어떠한 프로퍼티라도 글로벌 스코프나 펑션 스코프로부터 삭제될 수 없습니다.
    • 결국, delete는 글로벌 스코프의 어떤 함수도 삭제 할 수 없습니다. (함수 정의 또는 함수 표현식인지 여부에 따라서)
    • 오브젝트의 속성으로 있는 함수인 경우(글로벌 스코프를 제외하고)는 delete로 삭제할 수 있습니다.
  • letconst로 선언한 속성은 어느 스코프에 정의되어 있건 삭제 할 수 없습니다.
  • Non-configurable 속성은 삭제 할 수 없습니다. 이것은  Math, Array, Object와 같은 built-in objects의 속성들이나 Object.defineProperty() 같은 메소드로 만든 non-configurable속성들을 포함합니다.

간단한 예제입니다.

var Employee = {
  age: 28,
  name: 'abc',
  designation: 'developer'
}

console.log(delete Employee.name);   // returns true
console.log(delete Employee.age);    // returns true

// 아래 프로퍼티를 삭제하려고 시도하면
// 존재하지 않아 true를 리턴합니다.
console.log(delete Employee.salary); // returns true

Non-configurable properties

When a property is marked as non-configurable, delete won't have any effect, and will return false. In strict mode this will raise a SyntaxError.

var Employee = {};
Object.defineProperty(Employee, 'name', {configurable: false});

console.log(delete Employee.name);  // returns false

varlet and const create non-configurable properties that cannot be deleted with the delete operator:

var nameOther = 'XYZ';

// We can access this global property using:
Object.getOwnPropertyDescriptor(window, 'nameOther');  

// output: Object {value: "XYZ", 
//                  writable: true, 
//                  enumerable: true,
//                  configurable: false}

// Since "nameOther" is added using with the
// var keyword, it is marked as "non-configurable"

delete nameOther;   // return false

In strict mode, this would have raised an exception.

Strict vs. non-strict mode

When in strict mode, if delete is used on a direct reference to a variable, a function argument or a function name, it will throw a SyntaxError.

Any variable defined with var is marked as non-configurable. In the following example, salary is non-configurable and cannot be deleted. In non-strict mode, the delete operation will return false.

function Employee() { 
  delete salary;
  var salary;
}

Employee();

Let's see how the same code behaves in strict mode. Instead of returning false, the statement raises a SyntaxError.

"use strict";

function Employee() {
  delete salary;  // SyntaxError
  var salary;        
}

// Similarly, any direct access to a function
// with delete will raise a SyntaxError

function DemoFunction() {
  //some code
}

delete DemoFunction; // SyntaxError

Examples

// creates the property adminName on the global scope
adminName = 'xyz';            

// creates the property empCount on the global scope
// Since we are using var, this is marked as non-configurable. The same is true of let and const.
var empCount = 43;

EmployeeDetails = {
  name: 'xyz',
  age: 5,
  designation: 'Developer'
};

// adminName is a property of the global scope.
// It can be deleted since it is created without var.
// Therefore, it is configurable.
delete adminName;       // returns true

// On the contrary, empCount is not configurable, 
// since var was used.
delete empCount;       // returns false 

// delete can be used to remove properties from objects  
delete EmployeeDetails.name; // returns true 

// Even when the property does not exists, it returns "true"
delete EmployeeDetails.salary; // returns true 

// delete does not affect built-in static properties
delete Math.PI; // returns false 

// EmployeeDetails is a property of the global scope.
// Since it defined without "var", it is marked configurable
delete EmployeeDetails;   // returns true

function f() {
  var z = 44;

  // delete doesn't affect local variable names
  delete z;     // returns false
}

delete and the prototype chain

In the following example, we delete an own property of an object while a property with the same name is available on the prototype chain:

function Foo() {
  this.bar = 10;
}

Foo.prototype.bar = 42;

var foo = new Foo();

// Returns true, since the own property
// has been deleted on the foo object
delete foo.bar;           

// foo.bar is still available, since it 
// is available in the prototype chain.
console.log(foo.bar);

// We delete the property on the prototype
delete Foo.prototype.bar; 

// logs "undefined" since the property
// is no longer inherited
console.log(foo.bar);           

Deleting array elements

When you delete an array element, the array length is not affected. This holds even if you delete the last element of the array.

When the delete operator removes an array element, that element is no longer in the array. In the following example, trees[3] is removed with delete.

var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
delete trees[3];
if (3 in trees) {
    // this does not get executed
}

If you want an array element to exist but have an undefined value, use the undefined value instead of the delete operator. In the following example, trees[3] is assigned the value undefined, but the array element still exists:

var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
trees[3] = undefined;
if (3 in trees) {
    // this gets executed
}

Specifications

Specification Status Comment
ECMAScript Latest Draft (ECMA-262)
The definition of 'The delete Operator' in that specification.
Living Standard  
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'The delete Operator' in that specification.
Standard  
ECMAScript 5.1 (ECMA-262)
The definition of 'The delete Operator' in that specification.
Standard  
ECMAScript 1st Edition (ECMA-262)
The definition of 'The delete Operator' in that specification.
Standard Initial definition. Implemented in JavaScript 1.2.

Browser compatibility

Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)
Temporal dead zone ? ? 36 (36) ? ? ?
Feature Android Chrome for Android Edge Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)
Temporal dead zone ? ? ? 36.0 (36) ? ? ?

Cross-browser notes

Although ECMAScript makes iteration order of objects implementation-dependent, it may appear that all major browsers support an iteration order based on the earliest added property coming first (at least for properties not on the prototype). However, in the case of Internet Explorer, when one uses delete on a property, some confusing behavior results, preventing other browsers from using simple objects like object literals as ordered associative arrays. In Explorer, while the property value is indeed set to undefined, if one later adds back a property with the same name, the property will be iterated in its old position--not at the end of the iteration sequence as one might expect after having deleted the property and then added it back.

If you want to use an ordered associative array in a cross-browser environment, use a Map object if available, or simulate this structure with two separate arrays (one for the keys and the other for the values), or build an array of single-property objects, etc.

See also

문서 태그 및 공헌자

 이 페이지의 공헌자: Hou
 최종 변경: Hou,