Arrays are one of the most important data structures in JavaScript. They allow you to store a collection of data in a single variable. In this tutorial, we will discuss the basics of arrays in JavaScript.
An array is a collection of data that is stored in a single variable. The data in an array can be of any type, including strings, numbers, and objects.
To create an array, you use the array keyword followed by the name of the array. For example, the following code creates an array called colors:
var colors = [];
The array variable is an empty array. To add data to the array, you use the push() method. The push() method adds a new item to the end of the array. For example, the following code adds the string “red” to the colors array:
colors.push(“red”);
You can also use the push() method to add a number or an object to the array.
To access the data in an array, you use the index number of the item that you want to access. The index number starts at 0. For example, the following code prints the string “red” to the console:
console.log(colors[0]);
The following code prints the number 5 to the console:
console.log(colors[1]);
The following code prints the object {name: “John”} to the console:
console.log(colors[2]);
The length of an array is the number of items in the array. You can use the length property to get the length of an array. For example, the following code prints the length of the colors array to the console:
console.log(colors.length);
The following code prints the string “6” to the console:
console.log(colors.length);
The for…in loop is a looping construct that allows you to iterate through the items in an array. The for…in loop will iterate through the indexes of the array, not the values. For example, the following code prints the indexes of the colors array to the console:
console.log(colors.forEach(function(index) {
console.log(index);
}));
The following code prints the values of the colors array