High-level programming language.
Arrays are a fundamental part of JavaScript and are used to store multiple values in a single variable. They are incredibly versatile and are used in almost every JavaScript application. This article will cover the basics of creating, accessing, and modifying arrays in JavaScript.
In JavaScript, arrays can be created in two ways:
[]
.let fruits = ['apple', 'banana', 'cherry'];
new
keyword and the Array()
constructor.let fruits = new Array('apple', 'banana', 'cherry');
Array elements are accessed using their index number. The index of an array is zero-based, meaning the first element is at index 0, the second element is at index 1, and so on.
let fruits = ['apple', 'banana', 'cherry']; console.log(fruits[0]); // Outputs: apple
You can modify an existing element in an array by referring to the index number.
let fruits = ['apple', 'banana', 'cherry']; fruits[1] = 'blueberry'; console.log(fruits); // Outputs: ['apple', 'blueberry', 'cherry']
The length
property of an array returns the number of elements in the array. It is useful when you want to know the size of the array.
let fruits = ['apple', 'banana', 'cherry']; console.log(fruits.length); // Outputs: 3
JavaScript allows for arrays of arrays, also known as multidimensional arrays. This is useful when you want to store tables of data.
let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; console.log(matrix[1][2]); // Outputs: 6
In conclusion, arrays are a powerful tool in JavaScript. They allow you to store multiple values in a single variable, and provide numerous methods and properties to work with those values. Understanding arrays is fundamental to becoming proficient in JavaScript.