learn2kode.in

JavaScript Arrays

An Array in JavaScript is a special variable that can store multiple values in a single place.

Think of an array like a list:

Why Arrays Are Useful?

Without arrays:

let student1 = "John";
let student2 = "Emma";
let student3 = "Ryan";

With an array (clean & easier to manage):

let students = ["John", "Emma", "Ryan"];
1. Creating Arrays
A. Using Square Brackets (Recommended)
let colors = ["red", "green", "blue"];
B. Using new Array()
let numbers = new Array(10, 20, 30);
2. Accessing Array Values
Array indexing starts at 0.
let fruits = ["Apple", "Banana", "Mango"];

console.log(fruits[0]); // Apple
console.log(fruits[1]); // Banana
console.log(fruits[2]); // Mango
3. Changing Array Values
let fruits = ["Apple", "Banana", "Mango"];
fruits[1] = "Orange";

console.log(fruits); 
// ["Apple", "Orange", "Mango"]
4. Array Length

The .length property shows how many items are in the array:

let items = ["Pen", "Book", "Bag"];
console.log(items.length); // 3
5. Adding & Removing Elements

JavaScript gives many built-in methods:

A. Add Elements
1. push() → Adds at the end
2. unshift() → Adds at the beginning
B. Remove Elements
1. pop() → Removes from end
2. shift() → Removes from beginning
6. Looping Through Arrays
A. Using for loop
let cars = ["BMW", "Audi", "Tesla"];

for (let i = 0; i < cars.length; i++) {
  console.log(cars[i]);
}
B. Using for...of (Modern & Easy)
for (let car of cars) {
  console.log(car);
}
7. Useful Array Methods
1. indexOf() → Find position
let colors = ["red", "blue", "green"];
console.log(colors.indexOf("blue")); // 1
2. includes() → Check exists
colors.includes("green"); // true
3. slice() → Copy part of array
let sliced = colors.slice(0, 2); 
// ["red", "blue"]
4. splice() → Add/Remove from array
colors.splice(1, 1); 
// Removes 1 item at index 1
5. join() → Convert array to string
colors.join(", "); 
// "red, blue, green"
6. reverse()
7. sort()
Array Summary Table
Method Purpose Example
push() Adds item at end arr.push("x")
pop() Removes last item arr.pop()
shift() Removes first item arr.shift()
unshift() Adds item at beginning arr.unshift("x")
slice() Copy elements arr.slice(1,3)
splice() Add/Remove items arr.splice(1,1)
includes() Checks value exists arr.includes("x")
indexOf() Find index arr.indexOf("x")