Code Synopsis logo

What is an Array in JavaScript?

An array is a type of Javsascript object. Think of it as a box that holds data. In fact,declaring an empty array literally looks like creating a box:

const stuff = [];

Items in an array can be other containers, such as other arrays or objects, or simply primitive values. Arrays are magic because they are never full. You can always add more items.

Populating and editing an array

You can fill an array as you declare it:

const stuff = [ "word", "123", "[]", "{ name: 'Jane Smith' }" ];

Or you can add something later:

stuff.push('dog'); // ["word", "123", "[]", "{ name: 'Jane Smith' }", "dog"]

When you add an item using push() method, the new item appears at the end of the list.

If you want to remove something, you probably want to remove a specific item. You have to know how to select it.

Each item in an array is contained in a virtual, numbered slot. The first slot is 0, the second slot is 1, and so on. You can add items into specific slots, and you could end up with an empty slot.

The slot number is called the index. Here’s how you request the first item:

console.log(stuff[0]); // word

Here’s how you can remove a single item if you know the index number:

stuff.splice(0,1); // ["123", "[]", "{ name: 'Jane Smith' }", "dog"]

0 is the index of the item you want to remove. 1 is the number of items to remove starting from that index. If you leave out the second argument, you'll be deleting everything from the starting index on up. You can optionally include a third argument, a value, to replace the value at the starting index.

Another way to add or alter an item in an array is via direct assignment. Just remember that the array index starts with 0, or you may end up with unexpected results.

const array = [1,2,3]; array[4] = 4; console.log(array); // [1,2,3,,4]

Searching an array

If you know the value but not the index number, you can ask for it:

let indexOfDog = stuff.indexOf('dog'); console.log(indexOfDog); // 3

If the item you want is not there, you'll get back -1.

let indexOfCat = stuff.indexOf('cat'); console.log(indexOfCat); // -1

Need to know how many items are in the array?

console.log(Array.length()); // 4

The length property returns the highest index number + 1. Since array indexes start with 0, the last item in the array will have an index number equal to length - 1.

There’s a lot more to arrays, so be sure to read the references below.

Related posts:

Helpful references:

Have feedback on this topic?