JavaScript Arrays: The Basics
What happens when you want to work with a lot of data at once, wouldn’t it be nice if there was a way to keep track of all this information, a way to store it all in one place or in one variable where we could keep a list. Well, this is what Arrays are for, arrays are data structures that can hold multiple data values like a list, and we’ll explore how to create arrays, how to use arrays, and how arrays are structured.
- Create an Array: You can define a new array by listing values separated with commas between square brackets
[].
2. Accessing Array Elements: We can access elements in our array by referencing its position or location using an index. Each array element is numbered starting from zero and we can use these numbers as indices to access whatever value we want. One thing to be aware of is if you try to access an element at an index that does not exist, a value of undefined will be returned back.
Array Properties and Methods
Arrays have a range of properties and methods that make them powerful data structures. Properties are special pieces of information about a data structure, for example, length which is used to get the number of elements in an array. To access the length
property, type the name of the array, followed by a period .
, and the word length
. The length
property will then return the number of elements in the array.
Methods are special predefined functions that a data structure can call, here’s an overview of common array methods you should know:
- Push: This adds a new element to the end of an array. Also, the
push()
method returns the length of the array after an element has been added.
2. Pop: This removes the last element of an array. You don't need to pass a value with the pop()
method; instead, pop()
will always remove the last element from the end of the array. Also, pop()
returns the element that has been removed in case you need to use it.
3. Unshift: This adds an item to the beginning of an array.
4. Shift: This removes an item from the beginning of an array.
5. Splice: This can be used to add and remove items by its index position.
6. Slice: This copies parts of an array (It slices out a piece of an array into a new array).
The slice() method can also take two arguments, it selects elements from the start argument, and up to (but not including) the end argument.
7. Sort: Sorts the elements of an array in place and returns the array alphabetically. The sort method is ideal for strings and not numerical values as it is prone to make mistakes.
8. Concat(): It creates a new array by merging existing arrays to become one.
These are a few Array methods you should know as you’ll be making use of them frequently. For more information visit the MDN documentation or Freecodecamp to learn more. I hope this article was insightful, keep practicing and you’ll be an expert before you know it. Never stop learning.