TransWikia.com

How does array.length-- work?

Ethereum Asked by Alejandro Veintimilla on November 7, 2021

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?

One Answer

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

Answered by Shane Fontaine on November 7, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP