JavaScript Array
Object
The purpose of the array object is to store a series of values using a single variable name.
Online Examples
Create an array and assign values to it:
Example
You can find more examples at the bottom of the page.
What is an Array?
An array object uses a single variable name to store a series of values.
If you have a set of data (e.g., car names) stored in individual variables as shown below:
However, what if you want to find a specific car? And what if it's not just 3 cars, but 300? This would not be an easy task!
The best approach is to use an array.
An array can store all the values under one variable name and you can access any value by its variable name.
Each element in an array has its own ID, making it easy to be accessed.
Creating an Array
There are three methods to create an array.
The following code defines an array object named myCars
:
1: Regular way:
2: Concise way:
3: Literal:
Accessing an Array
By specifying the array name and the index number, you can access a specific element.
The following example accesses the first value of the myCars
array:
The following example modifies the first element of the myCars
array:
| | [0] is the first element of the array. [1] is the second element. | | --- | --- |
You Can Have Different Objects in an Array
All JavaScript variables are objects. Array elements are objects. Functions are objects.
Therefore, you can have different variable types in an array.
You can include object elements, functions, and arrays within an array:
Array Methods and Properties
Use predefined properties and methods of the array object:
Complete Array Object Reference Manual
You can refer to the complete reference manual on this site for all properties and methods of arrays.
The reference manual includes descriptions of all properties and methods (and more examples).
Complete Array Object Reference Manual
Creating New Methods
Prototype is a global constructor function in JavaScript. It can build new properties and methods for JavaScript objects.
Example: Creating a New Method
Array.prototype.myUcase = function() {
for (i = 0; i < this.length; i++) {
this[i] = this[i].toUpperCase();
}
}
The above example creates a new array method to convert lowercase characters to uppercase.
More Examples
Form a String from Array Elements - join()
Remove the Last Element of an Array - pop()
Add New Elements to the End of an Array - push()
Reverse the Order of Elements in an Array - reverse()
Remove the First Element of an Array - shift()
Select Elements from an Array - slice()
Sort an Array Alphabetically (Ascending) - sort()
Sort an Array Numerically (Ascending) - sort()
Sort an Array Numerically (Descending) - sort()
Add an Element at the 2nd Position of an Array - splice()