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.
What is an array?
An array is an ordered collection of values. Each value has a numeric position called an index.
const courses = ["HTML", "CSS", "JavaScript"];
console.log(courses);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.
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.
const topics = ["Variables", "Functions", "Arrays"];
console.log(topics[0]); // Variables
console.log(topics[2]); // ArraysArray length
length tells you how many elements an array currently contains.
const topics = ["HTML", "CSS", "JS"];
console.log(topics.length); // 3
console.log(topics[topics.length - 1]); // JSarray.length - 1 hota hai.Reading and updating items
You can read an item by index and assign a new value to that index.
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.
const tasks = ["HTML", "CSS"];
tasks.push("JavaScript");
console.log(tasks);
const removed = tasks.pop();
console.log(removed); // JavaScriptshift() and unshift()
unshift() adds items at the beginning. shift() removes the first item.
const queue = ["Riya", "Neha"];
queue.unshift("Aman");
console.log(queue);
queue.shift();
console.log(queue);includes() and indexOf()
includes() checks whether a value exists. indexOf() returns the first matching index or -1.
const skills = ["HTML", "CSS", "JavaScript"];
console.log(skills.includes("CSS")); // true
console.log(skills.indexOf("JavaScript")); // 2
console.log(skills.indexOf("Python")); // -1slice()
slice() returns a new array from part of an existing array without changing the original.
const chapters = [1, 2, 3, 4, 5];
const middle = chapters.slice(1, 4);
console.log(middle); // [2, 3, 4]
console.log(chapters); // unchangedsplice()
splice() can remove, replace or insert items and it changes the original array.
const items = ["HTML", "CSS", "Python"];
items.splice(2, 1, "JavaScript");
console.log(items); // ["HTML", "CSS", "JavaScript"]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.
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.
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.
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.
const scores = [80, 90, 70];
scores.forEach((score, index) => {
console.log(index, score);
});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.
const scores = [10, 20, 30];
const doubled = scores.map(score => score * 2);
console.log(doubled); // [20, 40, 60]
console.log(scores); // original unchangedfilter()
filter() creates a new array containing only items whose callback returns a truthy result.
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.
const scores = [30, 55, 80, 90];
console.log(scores.find(score => score >= 60)); // 80
console.log(scores.findIndex(score => score >= 60)); // 2If 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.
const scores = [60, 75, 90];
console.log(scores.some(score => score >= 90)); // true
console.log(scores.every(score => score >= 40)); // truereduce()
reduce() combines array values into one accumulated result.
const scores = [10, 20, 30];
const total = scores.reduce((sum, score) => sum + score, 0);
console.log(total); // 60reduce() 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.
const scores = [100, 20, 3];
const ascending = [...scores].sort((a, b) => a - b);
console.log(ascending); // [3, 20, 100]
console.log(scores); // original kept unchangedsort() 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.
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().
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.
const matrix = [
[1, 2],
[3, 4]
];
console.log(matrix[1][0]); // 3Array destructuring preview
Destructuring lets you unpack array positions into variables. We will revisit it in the Modern JavaScript chapter.
const skills = ["HTML", "CSS", "JavaScript"];
const [first, second] = skills;
console.log(first); // HTML
console.log(second); // CSSChoosing 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()orevery(). - Need one accumulated result? Use
reduce().
Beginner best practices
- Array names plural and meaningful rakho:
scores,courses. - Index
0se 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 (
-1orundefined) handle karo.
Common beginner mistakes
- First item ko index
1samajhna. array[array.length]ko last item samajhna.slice()aursplice()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?
lengthaur last index calculate kar sakte ho?push/pop/shift/unshiftka role clear hai?slice()vssplice()difference samajh aaya?for,for...ofaurforEach()me choose kar sakte ho?map/filter/find/reduceka 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.
- 5 course names ka array banao aur first/last item print karo.
- Third item update karo.
push()se ek item add aurpop()se remove karo.includes()se check karo ki"JavaScript"list me hai ya nahi.slice()se 3-item sub-array banao.splice()se ek wrong item replace karo.for...ofse saare items print karo.- Scores array par
map()se every score me 5 add karo. filter()se 40+ scores nikalo.reduce()se total aur average calculate karo.- Numeric array ko ascending sort karo without original mutate kiye.
- Direct assignment aur spread copy ka difference test karo.