The array data structure is used for ordered lists of data. What is unique about an array is that it contains key-value pairs that are numeric. The fact that the indices are based on numbers we can use those numbers to derive information like order sequence. An array is just an object with numeric keys, the length property, and useful helper methods.
Because an array is an object, there are no extra or special rules that apply to just arrays. You use an array just like an object. You may be wondering why it appears that we interact with an array differently than an object. For example, you have probably seen an array retrieving a value using bracket notation, but not dot notation like we often see with objects:
const myArray = [];
myArray[0] = "first value";
console.log(myArray[0]); // "first value"
And you are correct — we cannot use dot notation with numbers because properties cannot start with a number. That is why we need to use bracket notation instead. But the rules of bracket vs dot notation are exactly the same for arrays as they are for objects.
What are some examples of when you have used an array? Why did you choose to use an array rather than an object?
As a best practice, you want to make sure the data in the array is of the same type so if you have an array of strings you want to make sure that all the values in your arrays are also strings.
When I first started teaching this course in 2014, we didn't have a lot of the native array methods that are available today such as reduce, map, and filter so we had to write them from scratch or import libraries like
. These methods allow us to process arrays much more succinctly and are less error prone.
Arrays vs Strings
When working with strings you can also think about them as an array of characters. This is particularly helpful in interview settings when you're asked to do something with a string you can easily split() the string into an array of characters or array of words if you split it on a space: