obj
is an object, and property
is the name of its property.obj.property = undefined
sets the value of property to undefined
. The property is still there and appears if we iterate the properties of the object.let person = { name: 'John' };person.name = undefined;person.hasOwnProperty('name'); // truename in person; // trueObject.keys(person); // ['name']for (let p in person) {console.log(p);} // 'name'
delete obj.property
will remove the property from the object. Let's revisit the sample code above, now with delete person.name
:let person = { name: 'John' };delete person.name;person.hasOwnProperty('name'); // falsename in person; // falseObject.keys(person); // An empty array// Nothing is shown up in the Consolefor (let p in person) {console.log(p);}
delete
can't delete an inherited property.const car = { branch: 'Audi' };const a4 = Object.create(car);console.log(a4.branch); // 'Audi'delete a4.branch;console.log(a4.branch); // 'Audi'
undefined
:a4.branch = undefined;console.log(a4.branch); // undefined
delete
doesn't work with array:const array = [1, 2, 3, 4, 5];delete array[1];console.log(array); // [1, empty, 3, 4, 5]
splice
method.const array = [1, 2, 3, 4, 5];array.splice(2, 1);console.log(array); // [1, 2, 4, 5]
const array = [1, 2, 3, 4, 5];array.pop();console.log(array); // [1, 2, 3, 4]
const { name, ...rest } = { name: 'Foo', age: 20 };console.log(name); // 'Foo'console.log(rest); // { age: '20' }
const property = 'name';const { [property]: value, ...rest } = { name: 'Foo', age: 20 };console.log(value); // 'Foo'console.log(rest); // { age: '20' }