Arrays in JavaScript are used to store multiple values in a single variable. An array is a collection of data, and each data item in an array is called an element.
Here's an example of how to create an array in JavaScript:
let fruits = ['apple', 'banana', 'orange', 'grape'];
In this example, fruits
is an array that contains four elements: "apple", "banana", "orange", and "grape".
Arrays in JavaScript are zero-indexed, meaning the first element is at index 0, the second element is at index 1, and so on.
Here are some common operations you can perform on arrays in JavaScript:
Accessing array elements:
let fruits = ['apple', 'banana', 'orange', 'grape'];
console.log(fruits[0]); // "apple"
console.log(fruits[2]); // "orange"
Changing array elements:
let fruits = ['apple', 'banana', 'orange', 'grape'];
fruits[1] = 'kiwi';
console.log(fruits); // ["apple", "kiwi", "orange", "grape"]
Adding elements to an array:
let fruits = ['apple', 'banana', 'orange', 'grape'];
fruits.push('strawberry');
console.log(fruits); // ["apple", "banana", "orange", "grape", "strawberry"]
Removing elements from an array:
let fruits = ['apple', 'banana', 'orange', 'grape'];
fruits.splice(1, 2); // remove 2 elements starting from index 1
console.log(fruits); // ["apple", "grape"]
Looping through an array:
let fruits = ['apple', 'banana', 'orange', 'grape'];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Arrays in JavaScript have many built-in methods for performing different operations, including concat()
, slice()
, join()
, sort()
, and reverse()
. It's important to be familiar with these methods when working with arrays in JavaScript.