Day 6: Arrays and Their Everyday Methods
✅ Today you will learn
- Create arrays and read items by index
- Add and remove: push, pop, unshift, shift, splice
- Find: indexOf, includes, at()
- Copy and combine: slice, spread, concat, join
- Sorting numbers correctly and mutation pitfalls
🏢 In the real world
A cart is a list. So are today’s orders, a class’s marks, the sweets on the menu and the notifications in an app. Arrays are the most used data structure in JavaScript. A real bug from a school app: sorting marks [9, 80, 100, 45] “from lowest to highest” produced [100, 45, 80, 9]. You will see exactly why today.
Creating and reading arrays
const sweets = ['Kaju Katli', 'Ghewar', 'Rasmalai', 'Ladoo']; console.log(sweets[0]); // first item – index starts at 0 console.log(sweets[sweets.length - 1]); // last item console.log(sweets.at(-1)); // modern way to read from the end console.log(sweets.length); console.log(sweets[10]); // undefined – no error! sweets[1] = 'Malai Ghewar'; // change an item console.log(sweets); const mixed = ['Riya', 16, true, ['Maths', 'Science']]; // any types, even arrays console.log(mixed[3][1]);
Adding and removing
const cart = ['Ladoo'];
cart.push('Kaju Katli', 'Ghewar'); // add to the END
cart.unshift('Gift Box'); // add to the START
console.log(cart);
const last = cart.pop(); // remove from the END
const first = cart.shift(); // remove from the START
console.log(last, first, cart);
// splice(start, deleteCount, ...itemsToInsert) – change the middle
const menu = ['Kaju', 'Ghewar', 'Rasmalai', 'Ladoo'];
const removed = menu.splice(1, 2, 'Kalakand'); // remove 2 from index 1, insert 1
console.log(removed, menu);| Method | Does | Changes the array? | Returns |
|---|---|---|---|
| push(x) | Add to end | Yes | New length |
| pop() | Remove last | Yes | Removed item |
| unshift(x) | Add to start | Yes | New length |
| shift() | Remove first | Yes | Removed item |
| splice(i, n, …) | Remove/insert in middle | Yes | Array of removed items |
| slice(a, b) | Copy part from a to b-1 | No ⭐ | New array |
| concat / [...a, ...b] | Join arrays | No | New array |
| join(sep) | Array → string | No | String |
sPlice has a “P” for “Permanent change”: it edits the original. slice just copies. In React and modern apps prefer non-mutating methods so the old data stays intact.
Searching an array
const pinCodes = [302001, 302003, 302004, 302012];
const customerPin = 302003;
console.log(pinCodes.includes(customerPin) ? 'We deliver here ✅' : 'Not in delivery area');
console.log(pinCodes.indexOf(302004)); // position, or -1 if missing
console.log(pinCodes.indexOf(110001));
const tags = ['veg', 'sugar-free', 'gift'];
console.log(tags.join(' · '));
console.log('kaju,ghewar,ladoo'.split(',')); // string → arrayCopies, spread and the reference trap
const original = ['Kaju', 'Ghewar'];
const sameBox = original; // NOT a copy – both names point to one array
sameBox.push('Ladoo');
console.log(original); // changed too!
const realCopy = [...original]; // spread = new array
realCopy.push('Rasmalai');
console.log(original, realCopy);
const festive = [...original, 'Gift Box', ...['Soan Papdi']];
console.log(festive);Sorting – the number bug
const marks = [9, 80, 100, 45]; console.log([...marks].sort()); // ❌ sorts as TEXT: "100" < "45" < "80" < "9" console.log([...marks].sort((a, b) => a - b)); // ✅ ascending numbers console.log([...marks].sort((a, b) => b - a)); // ✅ descending const names = ['riya', 'Aarav', 'kabir']; console.log([...names].sort((a, b) => a.localeCompare(b))); // case-insensitive A–Z console.log(marks.toSorted ? 'toSorted() also exists and never mutates' : '');
Real task: a shopping list
<input id="item" placeholder="e.g. 1 kg Ghewar" aria-label="Item">
<button id="add">Add</button> <button id="undo">Remove last</button>
<p id="count"></p>
<ol id="list"></ol>
<script>
const list = [];
function render() {
document.querySelector('#list').innerHTML = list.map(x => `<li>${x}</li>`).join('');
document.querySelector('#count').textContent = `${list.length} item(s)`;
}
document.querySelector('#add').addEventListener('click', () => {
const box = document.querySelector('#item');
const text = box.value.trim();
if (text === '') return;
if (list.includes(text)) { alert('Already in the list'); return; }
list.push(text);
box.value = '';
render();
});
document.querySelector('#undo').addEventListener('click', () => { list.pop(); render(); });
render();
</script>Keep the data in an array, change the array, then call one render() function that rebuilds the HTML from the data. This “data → UI” idea is exactly how React works – you will use it in every project of this course.
🏅 Job skills unlocked today
Practice tasks
🏋️ Practice – do it yourself
Show solution
const queue = ['A101', 'A102', 'A103'];
const served = queue.shift();
queue.push('A104');
console.log('Served:', served);
console.log('Next:', queue[0], '| waiting:', queue.length, queue.join(', '));Show solution
const prices = [380, 900, 650, 500, 720]; const top3 = [...prices].sort((a, b) => b - a).slice(0, 3); console.log(top3, prices);
Quick quiz
🧠 Quick Quiz – test yourself
Interview corner
💼 Interview Corner
How do you copy an array, and what is a shallow copy?
[...arr], arr.slice() or Array.from(arr) create a new array, but nested objects/arrays inside are still shared references (shallow). For a deep copy use structuredClone(arr).
Why does [1, 10, 2].sort() return [1, 10, 2]?
Without a compare function sort converts items to strings and compares UTF-16 order, so "10" comes before "2". Pass (a, b) => a - b for numbers.
Summary
- Index from 0; length; at(-1) for the last item.
- push/pop/shift/unshift/splice change the array; slice/spread/concat copy.
- includes, indexOf, join, split for searching and converting.
- Sort numbers with (a, b) => a - b; keep data → render() → UI.
Day 7: objects – model real things (a product, an order, a student) with properties, methods, destructuring and JSON.
