A JavaScript array is a type of data structure used to store multiple data elements in a single, organized collection. Arrays are commonly used to store and manipulate data in a variety of forms, such as lists, tables, and graphs. Array elements can be accessed directly using their index numbers, which start at 0 and increase by one for each element.
Creating an array in JavaScript is simple. You can create an empty array using the square brackets [], or you can create an array with values by putting those values within the brackets, separated by commas. For example:
let emptyArray = [];
let arrayWithValues = [1, 2, 3];
Once you have an array, you can access and modify its elements using indexing. Indexing starts at 0, so the first element of an array will have an index of 0. For example, to access the first element of the arrayWithValues array created above, you would use arrayWithValues[0]
.
console.log(arrayWithValues[0]) // 1
You can also use the array’s length property to find the number of elements in the array. For example, to find the length of the arrayWithValues array, you would use arrayWithValues.length
.
console.log(arrayWithValues.length) // 3
Arrays also have a variety of methods that you can use to work with the data in the array. For example, the push()
method adds a new element to the end of the array, and the pop()
method removes the last element from the array.
var arr = [1, 2, 3];
arr.push(4);
console.log(arr); // [1, 2, 3, 4]
var arr = [1, 2, 3];
arr.pop();
console.log(arr); // [1, 2]
You can also use the sort()
method to sort the elements of an array in ascending or descending order, and the reverse()
method to reverse the order of the elements in the array.
var arr = [1, 2, 3];
arr.sort();
console.log(arr); // [1, 2, 3]
var arr = [1, 2, 3];
arr.reverse();
console.log(arr); // [3, 2, 1]
Leave a Reply