5
If you assign an index that is equal to or larger than the length of the array, the size of the array will increase to
accommodate the new element.
To access individual elements of an array, we simply use the numeric index of the ele‐
ment inside square brackets (similar to how we access properties on an object):
const
arr
=
[
'a'
,
'b'
,
'c'
];
// get the first element:
arr
[
0
];
// 'a'
// the index of the last element in arr is arr.length-1:
arr
[
arr
.
length
-
1
];
// 'c'
To overwrite the value at a specific array index, you can simply assign to it:
const
arr
=
[
1
,
2
,
'c'
,
4
,
5
];
arr
[
2
]
=
3
;
// arr is now [1, 2, 3, 4, 5]
, we’ll learn many more techniques for modifying arrays and their
contents.
Trailing Commas in Objects and Arrays
The alert reader may have already noticed that in these code samples, when the con‐
tent of objects and arrays spans multiple lines, there is a trailing (or dangling or termi‐
nal) comma:
const
arr
=
[
"One"
,
"Two"
,
"Three"
,
];
const
o
=
{
one
:
1
,
two
:
2
,
three
:
3
,
};
Many programmers avoid adding this because in early versions of Internet Explorer,
trailing commas produced an error (even though it has always been allowed in the
JavaScript syntax). I prefer trailing commas because I am frequently cutting and past‐
ing within arrays and objects, and adding things to the end of the object, so having
the trailing comma means I never need to remember to add a comma on the line
before; it’s simply always there. This is a hotly contested convention, and my prefer‐
ence is just that: a preference. If you find the trailing comma troubling (or your team’s
style guide prohibits its use), by all means, omit it.
50 | Chapter 3: Literals, Variables, Constants, and Data Types