0

Can anyone help me understand what an empty means in a JS array?

I just noticed an array in chrome devtools with an empty value. I created the one below, and by putting two commas together I can produce an empty (see below). Granted, I'm relatively new to JS, but since empty isn't a JS primitive I would have expected either:

a) a null or undefine3d value for a[3]

b) a.length to be 4

What does empty mean?

devtools screenshot

doub1ejack
  • 10,627
  • 20
  • 66
  • 125

1 Answers1

1

Array literals can include elisions, e.g.

[0,1,,3];

The two commas together mean "there is no element at index 2". Many stringified versions will show undefined at index 2, however that is misleading as there is no element at all at that position.

E.g.

let arr = [0,1,,3];

arr.forEach((v, i) => console.log(`index ${i} has value ${v}`)); 

console.log('stringified: ' + arr);
console.log('SO console:', arr);
console.log('JSON: ' + JSON.stringify(arr));

An alternative is to show "empty", which (IMHO) isn't really suitable either, it should be shown as in the literal (i.e. as for "stringified").

RobG
  • 142,382
  • 31
  • 172
  • 209
  • Would the downvoter care to explain their vote? Neither of the duplicates covers elisions, or "empty". – RobG Dec 04 '19 at 21:29