Understand Arrays
What is an array?
An array is a data structure that groups together data.. The data can be strings, numbers, booleans, or any mix of these data types.
Syntax
Inside an array is a comma separated list of data. An array starts and ends with a square brackets []
.
['bananas', 'oranges']; // this is an array - without a variable name to referencelet anArrayOfNumbers = [9, 1, 2, 4, 4, 5];let anArrayOfFruits = ['pineapples', 'bananas', 'oranges'];let aMixedArray = ['hello', 4, true, 'peace', 1002];
Access
To have access to an array item you use the index of the item within square brackets. Note the first item's index is 0.
let anArrayOfFruits = ['pineapples', 'bananas', 'oranges'];console.log(anArrayOfFruits[1]); // prints 'bananas'
Properties
length
The length property tells you the length of the array.
let anArrayOfNumbers = [9, 1, 2, 4, 4, 5];console.log(anArrayOfNumbers.length);// prints 6
Methods
pop()
The pop() method removes the last item of the array.
let anArrayOfNumbers = [9, 1, 2, 4, 4, 5];console.log(anArrayOfNumbers); // prints [9, 1, 2, 4, 4, 5]anArrayOfNumbers.pop();console.log(anArrayOfNumbers); // prints [9, 1, 2, 4, 4]
push()
The push() method adds an item onto the end of the array.
let anArrayOfNumbers = [9, 1, 2, 4, 4, 5];console.log(anArrayOfNumbers); // prints [9, 1, 2, 4, 4, 5]anArrayOfNumbers.push(12);console.log(anArrayOfNumbers); // prints [9, 1, 2, 4, 4, 5, 12]
reverse()
An array reverses the data in an array.
let anArrayOfNumbers = [9, 1, 2, 4, 4, 5];console.log(anArrayOfNumbers); // prints [9, 1, 2, 4, 4, 5]anArrayOfNumbers.reverse();console.log(anArrayOfNumbers); // prints [5, 4, 4, 2, 1, 9]