CHAPTER 8 · COLLECTIONS

JavaScript Arrays

Arrays ek hi variable me multiple values ko ordered collection ke form me store karte hain. Is chapter me array create karna, values read/update karna, useful methods aur real data processing patterns step by step samjhenge.

English + Hinglish42 min readPractice included

What is an array?

An array is an ordered collection of values. Each value has a numeric position called an index.

array.jsJS
const courses = ["HTML", "CSS", "JavaScript"];
console.log(courses);
Hinglish Explanation

Array ko numbered list samjho. Har item ki position hoti hai aur JavaScript me counting index 0 se start hoti hai.

Creating arrays

The most common syntax is an array literal using square brackets.

create.jsJS
const names = ["Aman", "Riya", "Neha"];
const scores = [80, 92, 76];
const mixed = ["BrounStack", 18, true, null];

Arrays can contain values of different types, although keeping related data together usually makes code easier to understand.

Indexes start at 0

The first item is index 0, second item index 1, and so on.

index.jsJS
const topics = ["Variables", "Functions", "Arrays"];
console.log(topics[0]); // Variables
console.log(topics[2]); // Arrays

Array length

length tells you how many elements an array currently contains.

length.jsJS
const topics = ["HTML", "CSS", "JS"];
console.log(topics.length); // 3
console.log(topics[topics.length - 1]); // JS
Common pattern: Last item ka index array.length - 1 hota hai.

Reading and updating items

You can read an item by index and assign a new value to that index.

update.jsJS
const levels = ["Beginner", "Intermediate", "Advanced"];
levels[1] = "Growing";
console.log(levels);

A const array binding cannot be reassigned to a different array, but the contents of the existing array can still change.

push() and pop()

push() adds one or more items to the end. pop() removes and returns the last item.

push-pop.jsJS
const tasks = ["HTML", "CSS"];
tasks.push("JavaScript");
console.log(tasks);

const removed = tasks.pop();
console.log(removed); // JavaScript

shift() and unshift()

unshift() adds items at the beginning. shift() removes the first item.

shift.jsJS
const queue = ["Riya", "Neha"];
queue.unshift("Aman");
console.log(queue);

queue.shift();
console.log(queue);
Performance note: Adding/removing at the start can require re-indexing many items. For beginner-sized arrays this is usually fine, but the behavior matters in larger workloads.

includes() and indexOf()

includes() checks whether a value exists. indexOf() returns the first matching index or -1.

search.jsJS
const skills = ["HTML", "CSS", "JavaScript"];
console.log(skills.includes("CSS")); // true
console.log(skills.indexOf("JavaScript")); // 2
console.log(skills.indexOf("Python")); // -1

slice()

slice() returns a new array from part of an existing array without changing the original.

slice.jsJS
const chapters = [1, 2, 3, 4, 5];
const middle = chapters.slice(1, 4);
console.log(middle);   // [2, 3, 4]
console.log(chapters); // unchanged

splice()

splice() can remove, replace or insert items and it changes the original array.

splice.jsJS
const items = ["HTML", "CSS", "Python"];
items.splice(2, 1, "JavaScript");
console.log(items); // ["HTML", "CSS", "JavaScript"]
slice vs splice

slice() generally copy/portion return karta hai without original change. splice() original array ko mutate karta hai.

Combining arrays

concat() and spread syntax can create a new combined array.

combine.jsJS
const frontend = ["HTML", "CSS"];
const scripting = ["JavaScript"];

const allA = frontend.concat(scripting);
const allB = [...frontend, ...scripting];
console.log(allA, allB);

Looping through arrays

A normal for loop is useful when you need the index.

for-array.jsJS
const topics = ["Variables", "Functions", "Arrays"];

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

for...of

for...of iterates directly over array values.

for-of.jsJS
const topics = ["HTML", "CSS", "JS"];

for (const topic of topics) {
  console.log(topic);
}

Use it when you want values and do not need manual index control.

forEach()

forEach() runs a callback once for each array item.

foreach.jsJS
const scores = [80, 90, 70];

scores.forEach((score, index) => {
  console.log(index, score);
});
Remember: forEach() is for side effects such as logging or updating UI. It does not build a transformed result array by itself.

map()

map() creates a new array by transforming every element.

map.jsJS
const scores = [10, 20, 30];
const doubled = scores.map(score => score * 2);

console.log(doubled); // [20, 40, 60]
console.log(scores);  // original unchanged

filter()

filter() creates a new array containing only items whose callback returns a truthy result.

filter.jsJS
const scores = [35, 80, 42, 25, 95];
const passed = scores.filter(score => score >= 40);
console.log(passed); // [80, 42, 95]

find() and findIndex()

find() returns the first matching element. findIndex() returns the first matching index.

find.jsJS
const scores = [30, 55, 80, 90];
console.log(scores.find(score => score >= 60)); // 80
console.log(scores.findIndex(score => score >= 60)); // 2

If no match is found, find() returns undefined and findIndex() returns -1.

some() and every()

some() checks whether at least one item matches. every() checks whether all items match.

checks.jsJS
const scores = [60, 75, 90];
console.log(scores.some(score => score >= 90)); // true
console.log(scores.every(score => score >= 40)); // true

reduce()

reduce() combines array values into one accumulated result.

reduce.jsJS
const scores = [10, 20, 30];
const total = scores.reduce((sum, score) => sum + score, 0);
console.log(total); // 60
Accumulator idea

reduce() me sum har item ke saath update hota hai. Starting value 0 yahan explicit di gayi hai, jo beginner code ko predictable banati hai.

Sorting arrays

Default sort() values ko strings ki tarah compare karta hai, so numeric arrays need a comparison function.

sort.jsJS
const scores = [100, 20, 3];
const ascending = [...scores].sort((a, b) => a - b);
console.log(ascending); // [3, 20, 100]
console.log(scores);    // original kept unchanged
Important: sort() mutates the array it is called on. Spread copy use karke original preserve kar sakte ho.

Arrays are reference values

Assigning an array to another variable does not automatically clone it; both bindings can point to the same array.

reference.jsJS
const original = [1, 2, 3];
const same = original;
same.push(4);

console.log(original); // [1, 2, 3, 4]

A shallow copy can be created with spread or slice().

copy.jsJS
const original = [1, 2, 3];
const copy = [...original];
copy.push(4);

console.log(original); // [1, 2, 3]
console.log(copy);     // [1, 2, 3, 4]

Nested arrays

An array can contain other arrays.

nested.jsJS
const matrix = [
  [1, 2],
  [3, 4]
];

console.log(matrix[1][0]); // 3

Array destructuring preview

Destructuring lets you unpack array positions into variables. We will revisit it in the Modern JavaScript chapter.

destructure.jsJS
const skills = ["HTML", "CSS", "JavaScript"];
const [first, second] = skills;

console.log(first);  // HTML
console.log(second); // CSS

Choosing the right pattern

  • Need index control? Use for.
  • Need simple values? Use for...of.
  • Need side effects per item? Use forEach().
  • Need a transformed array? Use map().
  • Need selected items? Use filter().
  • Need first match? Use find().
  • Need yes/no across collection? Use some() or every().
  • Need one accumulated result? Use reduce().

Beginner best practices

  • Array names plural and meaningful rakho: scores, courses.
  • Index 0 se start hota hai — ye always remember karo.
  • Original data preserve karna ho to mutating methods se pehle copy consider karo.
  • map(), filter(), reduce() ko purpose ke hisaab se choose karo, fashion ke hisaab se nahi.
  • Numeric sorting me compare function use karo.
  • Small readable callbacks prefer karo.
  • Missing search results (-1 or undefined) handle karo.

Common beginner mistakes

  • First item ko index 1 samajhna.
  • array[array.length] ko last item samajhna.
  • slice() aur splice() confuse karna.
  • sort() ko automatically numeric sort samajhna.
  • map() callback me value return karna bhoolna.
  • forEach() se result array expect karna.
  • Array copy samajhkar direct assignment kar dena.
  • Mutating method se original array accidentally change karna.
  • find() ka no-match result handle na karna.

Chapter checklist

  • Array create, read aur update kar sakte ho?
  • length aur last index calculate kar sakte ho?
  • push/pop/shift/unshift ka role clear hai?
  • slice() vs splice() difference samajh aaya?
  • for, for...of aur forEach() me choose kar sakte ho?
  • map/filter/find/reduce ka purpose samajh aaya?
  • Reference vs shallow copy ka basic difference clear hai?

Practice Task — Array Data Lab

Browser Console me ye exercises khud type karo.

  1. 5 course names ka array banao aur first/last item print karo.
  2. Third item update karo.
  3. push() se ek item add aur pop() se remove karo.
  4. includes() se check karo ki "JavaScript" list me hai ya nahi.
  5. slice() se 3-item sub-array banao.
  6. splice() se ek wrong item replace karo.
  7. for...of se saare items print karo.
  8. Scores array par map() se every score me 5 add karo.
  9. filter() se 40+ scores nikalo.
  10. reduce() se total aur average calculate karo.
  11. Numeric array ko ascending sort karo without original mutate kiye.
  12. Direct assignment aur spread copy ka difference test karo.