1

I'm having trouble understanding why people call

array.length--

after deleting an element in an array (as seen in this answer and many others). Why is there need for doing so? When is the length of an array evaluated? Or maybe I'm missing something obvious, what does array.length-- actually do?

1
  • It's the equivalent of popping the most recent item out of the array (which in that sense serves as a LIFO queue, or a stack if you will). – goodvibration Jul 21 '20 at 15:05
2

You must use array.length-- in order to accurately persist the length of the array.

The confusion comes from the fact that delete in Solidity does not actually delete an element from an array, but rather it just sets the element to it's default value (0 for a uint256, for example).

Observe the following code as an example:

uint256[] public testArray = [1,2,3,4,5];

// testArray = [1,2,3,4,5]
// testArray.length = 5

delete testArray[4];

// testArray = [1,2,3,4,0]
// testArray.length = 5

testArray.length--

// testArray = [1,2,3,4]
// testArray.length = 4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.