Arrays can contain any valid JavaScript value. It can store primitives (like Strings and Numbers) and objects (like objects, other arrays, and even functions).
Arrays can get difficult to read if everything is written in a single line. You can put each item on a new line to make it easier to read.
// One item in one line
const groceriesToBuy = [
'cabbage',
'tomato sauce',
'salmon'
]
// Arrays separated with new lines to make them easier to read
const arrays = [
[1, 2, 3],
[1, 2, 3]
]
// Objects separated with new lines to make them easier to read
const objects = [
{ firstName: 'Zell', lastName: 'Liew' },
{ firstName: 'Vincy', lastName: 'Zhang' }
]
Checking the number of items in an array
Arrays have properties and methods since they are objects. You can check the number of items in an array with the length property.
To get the value of an item in an array, you write the name of the array, followed by the position of the item in square brackets. This position is called the index.
// Where n is the index
const item = array[n]
In JavaScript:
First item has index 0,
Second item has index 1
Third item has index 2
And so on.
Indexes that start from zero are called zero-based indexes.
const strings = ['One', 'Two', 'Three', 'Four']
const firstItem = strings[0] // One
const secondItem = strings[1] // Two
const thirdItem = strings[2] // Three
const fourthItem = strings[3] // Four
If you provide an index that exceeds the number of items in the array, you’ll get undefined.
You can change the value of an item by assigning a value to it. You use = to assign a value.
const strings = ['One', 'Two', 'Three', 'Four']
// Assigning a new value to the first item
strings[0] = 1
console.log(strings) // [1, 'Two', 'Three', 'Four']
If you provide an index that exceeds the number of items in the array, JavaScript will help you create the intermediary items and fill them with undefined. (On Google Chrome, it may say empty. Nobody knows why they use empty).
For example, let’s say you have an array that contains four items. You add a string, ten as the tenth item.