JavaScript Arrays: 10 Code-Along Examples

Learn JavaScript arrays by running them. Ten copy-and-run examples covering creation, zero-based indexing, length, push, dynamic resizing, mixed types, Array.isArray, loops, and a complete shopping cart of objects.

The arrays introduction explains the idea: an array is an ordered list of values, indexed from zero, that grows and shrinks as you work with it. This workbook turns each concept into a small runnable example, from creating your first array through arrays of objects and loops, ending with a shopping cart that ties everything together. The HTML page is identical for every example, so set it up once and just swap the contents of script.js as you go.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="script.js" defer></script>
</head>
<body>
<p>Open the console to see the output.</p>
</body>
</html>

1. Creating an array

Square brackets create an array, with the values listed inside and separated by commas. One variable now holds a whole list.

const selectedColors = ['red', 'green', 'blue'];
console.log(selectedColors); // ['red', 'green', 'blue']

Before arrays, three colours would have needed three separate variables. selectedColors holds them all in one place, in a defined order, under a single name. That ordering is what makes an array different from a plain collection of values.

2. Zero-based indexing

Every item in an array has a numeric position called its index, and counting starts at zero. Read an item with bracket notation.

const selectedColors = ['red', 'green', 'blue'];
console.log(selectedColors[0]); // red, the FIRST item
console.log(selectedColors[1]); // green
console.log(selectedColors[2]); // blue, the THIRD item
console.log(selectedColors[3]); // undefined, there is no fourth item

The first item is [0], not [1], which is the classic beginner stumble. Asking for an index that does not exist, like [3] here, does not crash the program; JavaScript quietly returns undefined, which can hide bugs if you are not expecting it.

3. Updating an element

Bracket notation works for writing as well as reading. Assign to an index and that position’s value is replaced.

const selectedColors = ['red', 'green', 'blue'];
selectedColors[1] = 'yellow'; // replace the second item
console.log(selectedColors); // ['red', 'yellow', 'blue']

Note that this works even though selectedColors is a const. The const locks the variable to that one array; it does not freeze the array’s contents. You cannot reassign selectedColors to a different array, but you can change what is inside it.

4. The length property

length tells you how many items the array currently holds, and it updates automatically as the array changes.

const selectedColors = ['red', 'green', 'blue'];
console.log(selectedColors.length); // 3
console.log(selectedColors[selectedColors.length - 1]); // blue, the LAST item

Because indexing starts at zero, the last item always sits at length - 1. That little expression, array[array.length - 1], is the standard way to grab the final element, and it keeps working no matter how long the array grows.

5. Growing an array with push

push appends a new item to the end of the array, with no index arithmetic needed. It also returns the new length, which is occasionally useful.

const selectedColors = ['red', 'green'];
selectedColors.push('blue');
console.log(selectedColors); // ['red', 'green', 'blue']
console.log(selectedColors.length); // 3
const newLength = selectedColors.push('purple');
console.log(newLength); // 4

Compare this with assigning to selectedColors[2] by hand: push finds the end for you, so there is no risk of overwriting an existing item or leaving a gap. When you mean “add to the end,” push is the tool.

6. Dynamic resizing, and the gap trap

Arrays expand automatically if you assign to an index beyond the end. That flexibility is convenient, but it can create holes.

const scores = [10, 20];
scores[2] = 30; // one past the end: fine, array grows
console.log(scores); // [10, 20, 30]
scores[5] = 60; // three past the end: creates empty slots
console.log(scores); // [10, 20, 30, empty x 2, 60]
console.log(scores.length); // 6
console.log(scores[4]); // undefined

Assigning to index 5 of a three-item array does not error; JavaScript grows the array and leaves indexes 3 and 4 empty. Those holes read as undefined and count toward length, which is a recipe for confusing bugs. This is exactly why push is the safer habit for adding items.

7. Mixed types in one array

JavaScript arrays are dynamically typed, so a single array can hold strings, numbers, booleans, and even objects side by side.

const mixedBag = ['London', 18, true, { name: 'Sam' }];
console.log(mixedBag[0]); // London, a string
console.log(mixedBag[1]); // 18, a number
console.log(mixedBag[3].name); // Sam, reading into the object at index 3
console.log(typeof mixedBag[0]); // string
console.log(typeof mixedBag[1]); // number

Nothing stops you mixing types, and sometimes it is genuinely useful. In practice, though, most arrays hold items of one kind, because code that processes a list usually expects every item to have the same shape. Treat mixed arrays as the exception, not the default.

8. Arrays are objects underneath

typeof reveals a JavaScript quirk: an array reports itself as an object. The reliable way to check for an array is Array.isArray.

const selectedColors = ['red', 'green', 'blue'];
console.log(typeof selectedColors); // object, not "array"!
console.log(Array.isArray(selectedColors)); // true
console.log(Array.isArray('red')); // false

Under the hood an array is a special kind of object whose keys are the indexes, with extras like length and push layered on top. The practical takeaway is simple: never use typeof to detect an array, use Array.isArray instead.

9. Looping over an array

for loop visits every item in order, using the index as the counter and length as the stopping point. This is how you process a whole list with one block of code.

const selectedColors = ['red', 'green', 'blue'];
for (let i = 0; i < selectedColors.length; i++) {
console.log('Colour ' + (i + 1) + ': ' + selectedColors[i]);
}
// Colour 1: red
// Colour 2: green
// Colour 3: blue

Read the loop header in three parts: start i at zero, keep going while i is below length, and add one each pass. The condition uses < rather than <= precisely because indexing is zero-based; the last valid index is length - 1, so the loop must stop before i reaches length.

10. Putting it together: a shopping cart

The realistic shape of array data is an array of objects: a list of similar things, each with named properties. This final example combines creation, pushlength, indexing, and a loop into a small working cart.

const cart = [
{ name: 'Keyboard', price: 80 },
{ name: 'Mouse', price: 25 }
];
cart.push({ name: 'Monitor', price: 300 }); // a customer adds an item
console.log('Items in cart: ' + cart.length); // 3
console.log('First item: ' + cart[0].name); // Keyboard
let total = 0;
for (let i = 0; i < cart.length; i++) {
console.log(cart[i].name + ': £' + cart[i].price);
total = total + cart[i].price;
}
console.log('Total: £' + total);
// Keyboard: £80
// Mouse: £25
// Monitor: £300
// Total: £405

Every idea from the workbook appears here. The cart is an array of objects, push adds a product the way a real “add to basket” click would, cart[i].name indexes into the array and then reads a property, and the loop walks the whole list to build the total. Objects describe one thing; arrays hold many of them in order; together they are how JavaScript represents almost every list you will ever work with.

Work through these ten and you will have covered the whole arrays introduction: creating arrays, zero-based indexing, reading and updating by index, lengthpush, dynamic resizing and its gap trap, mixed types, the object-underneath quirk, loops, and arrays of objects. From here the natural next step in the series is control flow and loops in more depth, where the for loop you just used becomes a whole family of tools.

See you soon.

View Comments (3)

Leave a Reply

Prev Next

Subscribe to My Newsletter

Subscribe to my email newsletter to get the latest posts delivered right to your email. Pure inspiration, zero spam.

Discover more from Discuss Data Science, Machine Learning and Analytics

Subscribe now to keep reading and get access to the full archive.

Continue reading