Imagine you’re about to head to the grocery store, and you’ve got a list of items you need. In JavaScript, you can think of this “list” as an array. Arrays are special objects designed to hold list-like data.
Creating Arrays
Creating an array is as simple as using square brackets:
You can also add values right from the start, separating each item with a comma:
Array values
Arrays are pretty versatile. They can hold any valid JavaScript value, such as:
- Strings:
['One', "Two", "Three"]
- Numbers:
[1,2,3]
- Boolean:
[true, false, true]
- Objects:
[{name: "Reza"}, { name: "Iqlima"}]
- Other arrays:
[[1,2,3], [4,5,6]]
Reading and Formatting Arrays
For better readability, you can write each item on a new line:
Checking Array Length
Arrays come with handy properties and methods. To find out how many items are in an array, use the length
property:
Accessing Array items
To access an item in an array, use the array name followed by the item’s index in square brackets:
Remember, indexes start at 0, so the first item is at index 0, the second at index 1, and so on. If you try to access an index beyond the array’s length, you’ll get undefined
:
Accessing the Last item
To grab the last item in an array, use array.length - 1
You can also get other items from the end of the array:
Modifying Array items
Changing an item is straightforward. Just assign a new value to the desired index:
If you assign a value to an index beyond the current length of the array, JavaScript will file the gap with undefined