Arrays in JavaScript
Arrays are ordered collections of values that can hold multiple data types
(numbers, strings, objects, etc.). They are one of the most commonly used data
structures in JavaScript.
Creating Arrays
// Using array literal
let fruits = [
"Apple",
"Banana",
"Cherry"];
// Using the Array constructor
let numbers =
new
Array(
1,
2,
3,
4);
console.
log(fruits);
// ["Apple", "Banana", "Cherry"]
console.
log(numbers);
// [1, 2, 3, 4]
Accessing Elements
let fruits = [
"Apple",
"Banana",
"Cherry"];
console.
log(fruits[
0]);
// Apple (first element)
console.
log(fruits[
2]);
// Cherry (third element)
// Changing an element
fruits[
1] =
"Blueberry";
console.
log(fruits);
// ["Apple", "Blueberry", "Cherry"]
// Array length
console.
log(fruits.
length);
// 3
Common Array Methods
let fruits = [
"Apple",
"Banana",
"Cherry"];
// push() - Add to end
fruits.
push(
"Mango");
console.
log(fruits);
// ["Apple", "Banana", "Cherry", "Mango"]
// pop() - Remove from end
fruits.
pop();
console.
log(fruits);
// ["Apple", "Banana", "Cherry"]
// shift() - Remove from start
fruits.
shift();
console.
log(fruits);
// ["Banana", "Cherry"]
// unshift() - Add to start
fruits.
unshift(
"Strawberry");
console.
log(fruits);
// ["Strawberry", "Banana", "Cherry"]
// slice() - Copy part of array
let newFruits = fruits.
slice(
1,
3);
console.
log(newFruits);
// ["Banana", "Cherry"]
// splice() - Add/Remove items at specific index
fruits.
splice(
1,
1,
"Kiwi");
// Remove 1 element at index 1 and add "Kiwi"
console.
log(fruits);
// ["Strawberry", "Kiwi", "Cherry"]
Looping Through Arrays
For Loop
let fruits = [
"Apple",
"Banana",
"Cherry"];
for (
let i =
0; i < fruits.
length; i++) {
console.
log(fruits[i]);
}
for...of
Loop
for (
let fruit
of fruits) {
console.
log(fruit);
}
forEach()
Method
fruits.
forEach(
function(
fruit, index) {
console.
log(index, fruit);
});