7 - JavaScript Arrays
7 - JavaScript Arrays
by : Emmersive Learning
Join us :
Telegram : https://t.me/EmmersiveLearning
Youtube : https://www.youtube.com/@EmmersiveLearning/
JavaScript Arrays
Arrays in JavaScript are used to store multiple values in a single variable. Arrays
are one of the most common data structures in JavaScript. Here’s a detailed
guide on how to work with arrays:
1. Creating Arrays
Array constructor:
const fruits = new Array("apple", "banana", "berry");
Array elements are accessed by their index. Indexes start from 0 (zero-based
index):
fruits[1] = "orange";
console.log(fruits); // Output: ["apple", "orange", "cherry"]
4. Array Properties
Length: The length property returns the number of elements in the array:
console.log(fruits.length); // Output: 3
fruits.push("grape");
console.log(fruits); // Output: ["apple", "orange", "cherry",
"grape"]
fruits.pop();
console.log(fruits); // Output: ["apple", "orange", "cherry"]
shift(): Removes the first element from the array.
fruits.shift();
console.log(fruits); // Output: ["orange", "cherry"]
fruits.unshift("kiwi");
console.log(fruits); // Output: ["kiwi", "orange", "cherry"]
for loop:
fruits.forEach((fruit) => {
console.log(fruit);
});
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(matrix[1][2]); // Output: 6
8. Destructuring Arrays
You can use destructuring to extract values from an array into variables:
The spread operator (...) can be used to copy and merge arrays:
Copying an array:
const newFruits = [...fruits];
Merging arrays: