6

Was writing a function that takes in an array of numbers and returns true and the index if there is a missing number or false if there are no missing numbers. I Just noticed something about arrays that confuses me.

An array like

[,1,2,3,4] 

will print

[undefined,1,2,3,4]

The array starts with a comma, Output makes sense to me

But why does

[1,2,3,4,] // Notice that the array ends with a comma

print

[1,2,3,4]  

I would have assumed the output would be [1,2,3,4,undefined].

Does anyone know why this is so?

3 Answers 3

8

The trailing comma ("elision") is ignored:

If an element is elided at the end of an array, that element does not contribute to the length of the Array.

http://www.ecma-international.org/ecma-262/7.0/#sec-array-initializer

Note that only one comma is stipped on the right, so this [1,2,,] will be rendered as [1,2,undefined].

In Javascript arrays are just objects with a special length property, and an array initializer like

['a', 'b', 'c']

is a shortcut for

{
    "0": 'a', 
    "1": 'b', 
    "2": 'c',
    "length": 3
}

An elision makes the initializer skip the next index and increases the overall length, so this

['a', 'b', , 'c']

becomes this:

{
    "0": 'a', 
    "1": 'b', 
    "3": 'c'
    "length": 4
}

and two trailing elisions

['a', 'b', 'c', , ]

become

{
    "0": 'a', 
    "1": 'b', 
    "2": 'c', 
    "length": 4
}
Sign up to request clarification or add additional context in comments.

4 Comments

I'm not sure this is true In Javascript arrays are just objects with a special length property. From what point of view is this statement true? The user-facing API ?
But it also "inherits" all the Array.prototype methods, so length is not the only difference as stated.
That is so weird but thanks for giving me a perspective.
1

[,1,2,3,4] doesn't create [undefined,1,2,3,4]. It creates [empty, 1, 2, 3, 4]. It's a sparse array with a hole at the beginning.

From the documentation for Trailing commas:

JavaScript ignores trailing commas in arrays. JavaScript has allowed trailing commas in array literals since the beginning, and later added them to object literals (ECMAScript 5) and most recently (ECMAScript 2017) to function parameters.

But, if more than one trailing comma is used, a hole is produced:

var arr = [1, 2, 3,,,];
console.log(arr.length) // 5

Comments

0

The array would actually turn out to be [empty,1,2,3,4], here empty is basically a memory hole. This is an entry that has lost its memory reference. Link for detailed explanation is here

holes-arrays-es6

Comments

Your Answer

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.