How 'Delete' works in javascript?

Viewed 94

I'm little confused with js 'delete' operator.

for example

var data = { 
   list : [a, b, c]
}
var temp = data;

console.log(temp.list[2]); //Result 'c'
console.log(data.list[2]); //Result 'c'

delete temp.list[2];

console.log(temp.list[2]); //Result undefined
console.log(data.list[2]); //Result undefined why?

in this case, I have just only deleted temp.list[2] but data.list[2] shows undefined as well.

does 'delete' operator trace array address and delete data in it? is that why data.list[2] is also undefined? (because data.list[2] has address, not the actual data itself) I think there is explanation. can you help me?

4 Answers

Check out all the great references others have posted. But for a quick solution use the ES6 spread operator to create a copy.

    var data = { 
    list : ["a", "b", "c"]
    }
    var temp = {...data};  // this is now a copy not a reference

More on the spread operator

in other words this isnt a delete issue, its a reference vs copy issue

Complex types in JS are passed by reference, unless you explicitly take care of copying them.

What is happening here is:

var data = {        // <--\
   list : [a, b, c] // <----------------------------------------------
}                   // <--/                                           |
var temp = data;  // this is NOT a copy, but literally a pointer to -/

Try

var temp = Object.assign({}, data);

if you want a copy.

Your question touches on several topics:

First, delete operator removes the given property from the object, but when used to remove an element from an array, the array length is not affected:

let trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
delete trees[3];
alert(trees.length); //shows 5

If this is not what you want, consider using splice method instead. It is really powerful and can be used not only to remove elements.

let trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
trees.splice(3, 1);
alert(trees.length); //shows 4

Second, as everybody has already mentioned, var temp = data; doesn't create a copy of your object, it's just copies a reference. To make a fully identical shallow clone of your object, you could write:

let clone = Object.create(Object.getPrototypeOf(obj), 
    Object.getOwnPropertyDescriptors(obj));

This call makes a truly exact copy of obj, including all properties: enumerable and non-enumerable, data properties and setters/getters – everything, and with the right [[Prototype]], when Object.assign() method only copies enumerable and own properties from a source object to a target object

Related