Notes
An array is a special variable, which can hold more than one value:
const colors= ["Blue", "Red", "Black"];
It is a best practice to declare arrays with the const
keyword.
You can create an array with no elements and then add the elements in it.
Step 1: Define an array
const colors= [];
Let's define the elements of the colors array:
const colors= [];
cars[0] ="Blue";
cars[1] ="Red";
cars[2] ="Black";
You can also create an array using the new
keyword:
const colors = new Array("Blue", "Red", "Black");
You access an array element by referring to the index number:
const colors = ["Blue", "Red", "Black"];
document.write(colors [0]);
Output: Blue
Remember: Array indexes start with 0. [0] is the first element. [1] is the second element.
You can change any element of the array:
const colors = ["Blue", "Red", "Black"];
colors[2]="Orange"
document.write(colors);
Output: Blue,Red,Orange
The typeof operator in JavaScript returns "object" for arrays.
const colors = ["Blue", "Red", "Black"];
document.write(typeof(colors));
Output: object
The length
property of an array returns the length of an array
const colors = ["Blue", "Red", "Black"];
document.write(colors.length);
Output: 3
Remember: The length property is always one more than the highest array index.
You can access the last element of the array by subtracting 1 from the length of the array and use it as index:
const colors = ["Blue", "Pink", "Red", "Orange", "Black", "White"];
document.write(colors[colors.length-1]);
Output: White
You can use push()
method to add a new element to an array:
const colors = ["Blue", "Pink", "Red"];
colors.push("White";
document.write(colors);
Output: Blue,Pink,Red,White
Remember: push() method adds an element at the end of the array.