Array Object in JavaScript – Explained with Examples
An array object is an element used to bundle multiple unnamed values into a single item.
A pair of square brackets ([...]
) defines JavaScript’s array object.
Examples of a JavaScript Array Object
Let’s discuss some examples of an array object.
Example 1: An array with two unnamed values
Above is an array object containing two unnamed values.
Example 2: An array with four unnamed values
In the snippet above is an array object containing four unnamed values.
Let’s now discuss how to access the content of an array object.
How to Access an Array Object’s Value
You cannot access the content of an array object unless you put it in a variable and invoke it through the variable’s name.
Once you’ve kept your array in a variable, you can use the square bracket notation to access the array’s value.
Here’s the syntax:
In the snippet above, variableName
references the name of the variable containing your array.
On the other hand, index
refers to the position of items in an array object.
Array’s indexing starts at zero. In other words, the index of an array’s first item is 0
. The second value’s index is 1
. And the last item’s index is the array’s length
minus 1
.
For instance, consider this array object:
Here are the index positions of the array items above:
- Blue is at index 0
- White’s index position is 1
- Pink’s index is 2
- Green’s index position is 3
To access any value in the snippet above, you must put the array in a variable like so:
The colors[2]
code in the snippet above instructs the computer to get the color
array’s second index value.
Notice that each value in the array object above has no name. However, under the hood, JavaScript uses each item’s index position as its name.
In other words, behind the scenes, Blue
’s name is 0
, while Green
’s name is 3
.
So, technically, all array items have names.
However, users can not specify the names. Instead, JavaScript automatically uses each value’s index as its name.
Important Stuff to Know about an Array Object
Keep these six essential pieces of info in mind whenever you choose to use an array object.
- You can use JavaScript’s
shift()
method to remove an array’s first item. - To remove an array’s last element, use
pop()
. - Suppose you wish to copy part of an array without modifying it. In that case, use
slice()
. - To add or remove an item at any index position, use the
splice()
method. - You can use
push()
or thelength
property to add new items to the end of an array object. - Use unshift() to add new items to the beginning of an array object.