What delete in solidity does is not what you think.

What delete in solidity does is not what you think.

When we hear the word delete, the first thing that comes to our mind is to make things disappear. And when we use it, we want to make things vanish completely be it files, text or anything.

In the world of programming, different languages have different methods of manipulating variables and data structures.

The delete method would come in handy in scenarios when we want to make elements in data structures or variables disappear.

For example in javascript, to make the last element from an array disappear, we use pop() method on the array.

Notice, that this method removes an element from the array and also reduces the array size.

Well, in solidity, we have a keyword delete that is used to manipulate variables and data structures.

You would think that using the delete method on a variable or an element in solidity would make it disappear. But that's not true.

Using an array of numbers as an example, we will write a simple solidity program to help us understand the working of the delete method.

first let's declare our array of numbers

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.0 <0.9.0;

contract simpleProgram {

uint[] array  = [1,2,3,4,5];

We will also write two functions; one that returns the size of the array.


function arrayLength() public view returns(uint){ 
return array.length;
}

And another, that will call the delete method on the array element at index 1

function deleteElement() public { 
delete array[1];
 }

Now, if you want to remove the element at index 1 of the array(which is 2), you would expect two things to happen.

One is that the element(2) will disappear from that position in the array, and the second is that the length of the array will reduce by 1 since one element has been removed.

if you try to check the length of the array after the operation, you notice that the length has not changed at all. Also, if you access the elements in the array, you will see that the element at index 1 was replaced with a zero.

So what happened! it turns out that the delete method did not remove the element at the index we specified, but rather it reset the value at index 1 to the default value of the data type(in our case 0 for uint data type)

So now you know, that the delete method in solidity does not remove the element completely but rather, it resets the value to the default concerning the data type of that element.

Happy coding, see you soon!!!