3 ms·
One of the very rare times I've lost my cool in a Stack Overflow comment thread was an argument about a name. Not a function or variable name, but a piece of te
by Stratoscope 9y ago
One of the very rare times I've lost my cool in a Stack Overflow comment thread was an argument about a name. Not a function or variable name, but a piece of terminology.
The question was from someone who was using this to detect whether a JavaScript array was empty:
if( JSON.stringify(array) === "[]" ) { /* it's empty */ }
They wanted to know if this was a good way to do it or if there was a better way. Naturally, several answers showed up within seconds suggesting the usual (and much faster) way of doing it:
if( array.length === 0 ) { /* it's empty */ }
Then someone commented that if you did "new Array(23)", this test would give incorrect results: it would report that the array was not empty even though it actually is empty.
I replied that it didn't make sense to call this an empty array, because it had a length of 23, and it was no different from "[ undefined, undefined, ...23 times... ]", and surely that wouldn't be considered an "empty array", would it?
Of course I was wrong on that detail. This person explained that "new Array(23)" doesn't create an array of 23 elements, it creates an array with 23 empty slots but no elements at all, so regardless of its .length it should also be considered an empty array. He pointed out that `array.forEach()` skips over empty slots, and gave the analogy of a schoolbus: if a bus has 23 seats and no one is sitting in any of them, you could call it an empty bus. So by analogy an array of 23 empty slots should be called an empty array.
Eventually we just agreed to disagree.
At this point the poor OP must have been getting pretty confused. They were already using a test that would have called "new Array(23)" a non-empty array, just like the .length test does.
And then someone else came along asking which was really the right way to test for an empty array, .length or something else that would take into account the possibility of an array with empty slots and no elements.
Empty array or not? Naming things is a minefield!
- firethief 9y agoThat is a wrong question. Trying to find the "best" meaning of "empty" in the abstract is mooted by the DWIM nature of the language. Javascript does not have a concept of "empty"; what do you really need to know about the variable?
- dwaltrip 9y agoBingo. The above example reminds me of the old situation where one asks about X when they really care about Y.
- flukus 9y ago> Empty array or not? Naming things is a minefield! I'll go for option 3 and say that the naming error was further up the stack and that they really wanted a list and not an array. A list would have both a length (0) and a capacity (23).