Java Reference
In-Depth Information
Figure 3.1. A stack of pizza boxes
We can create an array to represent Donatello's pile of pizza boxes in JavaScript by creating
an empty array literal called
pizzas
:
var pizzas = [];
Each empty box can be thought of as representing an empty
element
in this array.
To find out what is in box 0, Donatello can open it up and peek inside. In JavaScript, we
can find out the value of element 0 in the
pizzas
array using the following code:
pizzas[0];
<< undefined
To access a specific value in an array, we write its position in the array in square brackets
(this is known as its
index
). If an element in an array is empty,
undefined
is returned.
Adding Values to Arrays
If Donatello wants to put a Margherita pizza in box 0, he just needs to open the box and put
it inside. To place the string "
Margherita
" inside the first element of our
pizzas
array,
we need to assign it to element
0
, like so:
pizzas[0] = "Margherita";

