MDN’s new design is in Beta! A sneak peek: https://blog.mozilla.org/opendesign/mdns-new-design-beta/

delete operator

Esta tradução está incompleta. Por favor, ajude a traduzir este artigo.

operador delete remove uma propriedade de um objeto.

Sintaxe

delete expression 

onde expression deve referenciar a propriedade, e.g.:

delete object.property
delete object['property']

Parâmetros

object
O nome do objeto, ou a expressão de referencia do objeto.
property
A propriedade a ser deletada.

Valor de retorno

true para todos os casos exceto quando uma propriedade é própria e não-configurável, nesse caso, false é retornado no modo não-strict.

Exceções

Throws Global_objects/SyntaxError no modo strict se a propriedade é própria e não-configurável.

Descrição

Ao contrário do que se imagina, o operador delete não tem relação direta com a desalocação de memória. O gerenciamento de memória é feito indiretamente através das quebras de referência, veja a página de gerenciamento de memória para obter mais detalhes.

O operador delete remove uma determinada propriedade do objeto. Em caso de sucesso, será retornado true, senão false será o retorno. Contudo, é importante considerar os seguintes cenários:

  • Se a propriedade que você está tentando deletar não exisitir, delete terá efeito e irá retornar true
  • If a property with the same name exists on the object's prototype chain, then, after deletion, the object will use the property from the prototype chain (in other words, delete only has an effect on own properties).
  • Any property declared with var cannot be deleted from the global scope or from a function's scope.
    • As such, delete cannot delete any functions in the global scope (whether this is part from a function definition or a function expression).
    • Functions which are part of an object (apart from the global scope) can be deleted with delete.
  • Any property declared with let or const cannot be deleted from the scope within which they were defined.
  • Non-configurable properties cannot be removed. This includes properties of built-in objects like Math, Array, Object and properties that are created as non-configurable with methods like Object.defineProperty().

The following snippet gives a simple example:

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

console.log(delete Employee.name)   // retorna true
console.log(delete Employee.age)    // retorna true

// Quando se tenta traduzir uma propriedade que 
// não existe, o retorno será true 
console.log(delete Employee.salary) // retorna true

Propriedades não-configuráveis

Quando uma propriedade é marcada como não-configurável, delete não terá efeito, e irá retornar false. Em modo strict isso irá lançar uma exceção do tipo SytaxError.

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

Em modo strict, isso teria lançado uma exceção.

Modo strict vs. não-strict

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()

Vamos ver o comportamento do mesmo código no modo strict. Em vez de retornar false, o trecho de código irá lançar uma exceção do tipo SyntaxError.

"use strict";

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

// Igualmente, qualquer acesso direto a uma função
// com delete irá lançar uma exceção do tipo SyntaxError

function DemoFunction() {
  //some code
}

delete DemoFunction; // SyntaxError

Exemplos

// 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);           

Removendo elementos de um array

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
}

Especificações

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

Compatibilidade dos navegadores (browser)

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes)
Temporal dead zone ? 36 (36) ? ? ?
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (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.

So, if you want to simulate an ordered associative array in a cross-browser environment, you are forced to either use two separate arrays (one for the keys and the other for the values), or build an array of single-property objects, etc.

Veja também

Etiquetas do documento e colaboradores

 Colaboradores desta página: edgardleal, NandoFarias
 Última atualização por: edgardleal,