0

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
2
  • Is your question why length reports three instead of four, or something else? Commented Feb 2, 2021 at 18:31
  • yeah it's about length Commented Feb 2, 2021 at 18:32

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.