JavaScript Arrays – Create, Access, Modify

What is an Array?

An array is a special variable that can hold multiple values. For example, instead of storing 5 numbers in 5 variables, you can store them in a single array.

let numbers = [10, 20, 30, 40, 50];

Creating Arrays

1. Using Square Brackets (Recommended)

let fruits = ["Apple", "Banana", "Mango"];

This creates an array named fruits with 3 values.

2. Using new Array()

let scores = new Array(85, 90, 75);

This also creates an array, but the square brackets method is preferred.

Accessing Array Elements

let cities = ["Mumbai", "Paris", "London"];
console.log(cities[0]); // "Mumbai"

Use the index number to access a value. Note: Index starts from 0.

Get Array Length

let cities = ["Mumbai", "Paris", "London"];
console.log(cities.length); // 3

.length tells how many items are in the array.

Updating Elements

cities[1] = "Tokyo";
console.log(cities); // ["Mumbai", "Tokyo", "London"]

This changes the second value from "Paris" to "Tokyo".

Adding Elements

1. Add at End using push()

cities.push("Delhi");
console.log(cities); // ["Mumbai", "Tokyo", "London", "Delhi"]

push() adds a value at the end.

2. Add at Beginning using unshift()

cities.unshift("New York");
console.log(cities); // ["New York", "Mumbai", "Tokyo", "London", "Delhi"]

unshift() adds value at the beginning.

3. Add at Specific Index

cities[5] = "Sydney";
console.log(cities);

If you use a new index, it adds a value there. Missing indexes become undefined.

Removing Elements

1. Remove Last Element using pop()

let last = cities.pop();
console.log(last); // "Sydney"
console.log(cities);

pop() removes the last value and returns it.

2. Remove First Element using shift()

let first = cities.shift();
console.log(first); // "New York"
console.log(cities);

shift() removes the first value and returns it.

3. Remove Specific Element using filter()


let cities = ["Mumbai", "Paris", "London", "Tokyo"];
let updatedCities = cities.filter(city => city !== "London");
console.log(updatedCities); // ["Mumbai", "Paris", "Tokyo"]

Use filter() to create a new array without unwanted values.

Looping Through an Array

1. forEach()

cities.forEach(city => console.log(city));

Goes through each element and runs the function.

2. for Loop


for(let i = 0; i < cities.length; i++) {
  console.log(cities[i]);
}

Classic loop using index numbers.

3. for...of Loop


for(let city of cities) {
  console.log(city);
}

Loop directly through the values.

4. for...in Loop


for(let index in cities) {
  console.log(cities[index]);
}

Loop through the index positions.

Summary

  • .push() – Add to end
  • .unshift() – Add to start
  • .pop() – Remove from end
  • .shift() – Remove from start
  • .length – Get size
  • .filter() – Remove specific values
  • .forEach() – Loop through each value