Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it okay to deliberately skip array elements using the comma operator?

Tags:

javascript

var array = [,, "cat", "dog"];

This will create an array with two empty values (so that I can use them later on). I can't think of any other way to do this without doing the slow and tedious array[2] = "cat"; array[3] = ... Is this a good way to do this. Or is there another recommended practice that emulates this ability.

like image 221
David G Avatar asked Feb 24 '23 02:02

David G


1 Answers

Yes. The holes will not be defined, but contribute to the Array length.

The spec [ref] allows it:

Array elements may be elided at the beginning, middle or end of the element list. Whenever a comma in the element list is not preceded by an AssignmentExpression (i.e., a comma at the beginning or after another comma), the missing array element contributes to the length of the Array and increases the index of subsequent elements. Elided array elements are not defined.

However, as pointed by pimvdb, the fact that it's possible does not necessarily imply that it's a good practice.

like image 199
Arnaud Le Blanc Avatar answered Feb 25 '23 16:02

Arnaud Le Blanc