I have defined an empty object (associative array)
obj = {}
If I try to query any parameter, it will return undefined as it is empty.
>> console.log(obj.id)
undefined
now I assign a value to id
>> obj.id = 123
>> console.log(obj.id)
123
Suppose I want to delete the id attribute which of these 2 is more convenient
obj.id = undefined
either
delete obj.id
when I consult the independent attribute of which I have used it will return undefined but if I do console.log()
only the object I have something different:
For the first case:
>> console.log(obj)
{id: undefined}
Instead for the second case:
>> console.log(obj)
{}
Which is the best, there is another alternative.
In this world of programming, it is not that one thing is better than another, but rather the one that best suits your needs.
Using delete is sooo slow and can affect your app's performance if you delete thousands and thousands of properties, but are you really going to delete that many properties? If you delete some of them, your application will probably slow down by about 200 milliseconds, something that nobody will notice. However, if you are going to store your objects in a non-rational database or you simply have to send objects to the server and users have slow connections, it is better to spend a few milliseconds deleting properties; I have worked with satellite networks and it is a headache to send large things by request.
Setting it to undefined is faster but you will have a lot of garbage dragging, which if it doesn't affect you there won't be any problem.
I leave you a benchmark where you can see that in one second they put 296,204,746 objects in a defined and only 10,851,554 with delete (approx)
So use the one that suits you best or with which you can have a cleaner and more readable code so that maintenance is more efficient.
to Delete an Object
javascript
you must use the worddelete
perform the command
obj.id = undefined
is to initialize the variable. If you want to send theJSON
without the valueid
you must usedelete
, otherwise if you want to fill a form with initial values, you are forced to send the value to your Backend you must declare the variables as shown In the example visualize that in both ways it is undefined but when you consult if the element exists in the object it exists and it prints it for youTo delete a property of an object in JavaScript use the operator
delete
since assigning the valueundefined
does not delete it.The advantage is that it
delete
deletes the property and therefore memory is freed and going through the properties of the object is faster.Reference