With a JavaScript Array, I can reset it to an empty state with a single assignment:
array.length = 0;
This makes the Array \"appear\" empty
ES5 solution can be:
// for enumerable and non-enumerable properties
Object.getOwnPropertyNames(obj).forEach(function (prop) {
delete obj[prop];
});
And ES6 solution can be:
// for enumerable and non-enumerable properties
for (const prop of Object.getOwnPropertyNames(obj)) {
delete obj[prop];
}
Regardless of the specs, the quickest solutions will generally be:
// for enumerable and non-enumerable of an object with proto chain
var props = Object.getOwnPropertyNames(obj);
for (var i = 0; i < props.length; i++) {
delete obj[props[i]];
}
// for enumerable properties of shallow/plain object
for (var key in obj) {
// this check can be safely omitted in modern JS engines
// if (obj.hasOwnProperty(key))
delete obj[key];
}
The reason why for..in should be performed only on shallow or plain object is that it traverses the properties that are prototypically inherited, not just own properties that can be deleted. In case it isn't known for sure that an object is plain and properties are enumerable, for with Object.getOwnPropertyNames is a better choice.