I am not able to understand if there is an array of empty values as:
let arr=[,,,];
and I try to log the length then I get 3 instead of 4
let arr=[,,,];
console.log('length',arr.length);
console.log('arr[1]',arr[1]);
j08691
209k33 gold badges269 silver badges281 bronze badges
asked Feb 2, 2021 at 18:28
Varun Sukheja
6,6848 gold badges67 silver badges103 bronze badges
1 Answer 1
Trailing commas are optional in array literals (in modern JS, at least). When you have
[<valid array list>,]
this is equivalent to
[<valid array list>]
So
[,,,]
is like
[undefined,undefined,undefined,]
The specification calls this construction [ ElementList , Elision(opt) ]
where Elision is the optional trailing comma.
If an element is elided at the end of an array, that element does not contribute to the length of the Array.
answered Feb 2, 2021 at 18:31
CertainPerformance
374k55 gold badges354 silver badges359 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js
lengthreports three instead of four, or something else?