Array in JavaScript

๐Ÿ“š What is an Array?

An Array in JavaScript is a special variable that holds a list of values. These values can be of any type โ€” numbers, strings, objects, even other arrays! Arrays are ordered and indexed, starting at 0.

>>โ€œArrays turn scattered data into structured sequences.โ€ ๐Ÿง 

๐Ÿ“ฆ Creating an Array

Basic Array Creation

let fruits = ["๐ŸŽ", "๐ŸŒ", "๐Ÿ‡"];
let numbers = [1, 2, 3, 4, 5];
let mixed = [42, "hello", true, null];

Note

๐Ÿ’ก You can store any data type โ€” even functions or objects โ€” in an array.

๐Ÿ”ข Accessing Array Elements

Use square brackets with the index to access elements.

Access Elements

let fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]); // "apple"
console.log(fruits[2]); // "cherry"

Note

๐Ÿ“Œ Array indices start at 0, not 1.

โœ๏ธ Modifying Elements

Change Array Elements

let colors = ["red", "blue"];
colors[1] = "green";
console.log(colors); // ["red", "green"]

โž• Common Array Methods

  • push() โ€“ Add to end
  • pop() โ€“ Remove from end
  • shift() โ€“ Remove from start
  • unshift() โ€“ Add to start
  • length โ€“ Get number of elements

Using Array Methods

let items = [1, 2];
items.push(3);      // [1, 2, 3]
items.pop();        // [1, 2]
items.unshift(0);   // [0, 1, 2]
items.shift();      // [1, 2]

๐Ÿ” Looping Through Arrays

for Loop

let names = ["John", "Jane", "Joe"];
for (let i = 0; i < names.length; i++) {
  console.log(names[i]);
}

forEach Method

names.forEach(function(name) {
  console.log(name);
});

Note

๐Ÿ’ก forEach is a cleaner way to loop, especially for readability.

๐Ÿ“ Useful Array Methods

  • map() โ€“ Transform each item
  • filter() โ€“ Return items that match a condition
  • find() โ€“ Return the first match
  • includes() โ€“ Check if item exists
  • sort() โ€“ Sort items

Example: filter and map

let scores = [40, 80, 95, 60];
let passed = scores.filter(score => score > 60);
let doubled = scores.map(score => score * 2);

๐Ÿงช Checking Arrays

Use Array.isArray() to confirm if a value is an array.

Check if it's an Array

console.log(Array.isArray([1, 2, 3])); // true
console.log(Array.isArray("hello")); // false

๐Ÿ“š Summary Table

OperationMethodDescription
Add at endpush()Adds one or more items
Remove from endpop()Removes the last item
Add at startunshift()Adds to the front
Remove from startshift()Removes the first item
LoopforEach()Runs a function for each item

๐ŸŒ Useful Resources

>>โ€œArrays are not just lists โ€” theyโ€™re the foundation of structured, powerful data manipulation in JavaScript.โ€ ๐Ÿ”ง