Javascript array
Created By: chatGPT
In JavaScript, an array is a data structure that can hold multiple values in a single variable. Arrays can store data of any type, including numbers, strings, objects, and even other arrays.
// Creating an array
let fruits = ['apple', 'banana', 'orange'];
To access an element in an array, you use its index, which starts at 0 for the first element. For example, to access the first fruit in the array, you would do the following:
console.log(fruits[0]); // Output: apple
You can also modify elements in an array by using their index. To change the second fruit to 'mango', you can do the following:
fruits[1] = 'mango';
console.log(fruits); // Output: ['apple', 'mango', 'orange']
Arrays come with many built-in methods that make it easy to manipulate data. For example, the push method adds a new element to the end of the array, while the pop method removes the last element.
// Adding a new fruit
fruits.push('grape');
console.log(fruits); // Output: ['apple', 'mango', 'orange', 'grape']
// Removing the last fruit
fruits.pop();
console.log(fruits); // Output: ['apple', 'mango', 'orange']
Another useful method is forEach, which allows you to iterate over each element in the array. This is particularly handy when you want to perform an operation on each item.
fruits.forEach(function(fruit) {
console.log(fruit);
}); // Output: apple, mango, orange