Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🟨 Days 1–7 – JavaScript Fundamentals  ·  Day 06

Day 6: Arrays and Their Everyday Methods

⏱ 85 min📶 Beginner🎯 100% self-study
Day 6 / 30

✅ 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

JavaScript
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]);
Kaju Katli Ladoo Ladoo 4 undefined [ 'Kaju Katli', 'Malai Ghewar', 'Rasmalai', 'Ladoo' ] Science

Adding and removing

JavaScript
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);
[ 'Gift Box', 'Ladoo', 'Kaju Katli', 'Ghewar' ] Ghewar Gift Box [ 'Ladoo', 'Kaju Katli' ] [ 'Ghewar', 'Rasmalai' ] [ 'Kaju', 'Kalakand', 'Ladoo' ]
MethodDoesChanges the array?Returns
push(x)Add to endYesNew length
pop()Remove lastYesRemoved item
unshift(x)Add to startYesNew length
shift()Remove firstYesRemoved item
splice(i, n, …)Remove/insert in middleYesArray of removed items
slice(a, b)Copy part from a to b-1No ⭐New array
concat / [...a, ...b]Join arraysNoNew array
join(sep)Array → stringNoString
💡 slice vs splice – remember with one letter

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

JavaScript
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 → array
We deliver here ✅ 2 -1 veg · sugar-free · gift [ 'kaju', 'ghewar', 'ladoo' ]

Copies, spread and the reference trap

JavaScript
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);
[ 'Kaju', 'Ghewar', 'Ladoo' ] [ 'Kaju', 'Ghewar', 'Ladoo' ] [ 'Kaju', 'Ghewar', 'Ladoo', 'Rasmalai' ] [ 'Kaju', 'Ghewar', 'Ladoo', 'Gift Box', 'Soan Papdi' ]

Sorting – the number bug

JavaScript
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' : '');
[ 100, 45, 80, 9 ] [ 9, 45, 80, 100 ] [ 100, 80, 45, 9 ] [ 'Aarav', 'kabir', 'riya' ] toSorted() also exists and never mutates

Real task: a shopping list

HTML + JavaScript
<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>
▶  push, pop, includes and join working together
🧠 render() pattern

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

✔ Create arrays and access items safely✔ Add, remove and insert with the right method✔ Search with includes/indexOf and convert with join/split✔ Copy with spread and sort numbers correctly

Practice tasks

🏋️ Practice – do it yourself

Task 1: Given the queue ["A101", "A102", "A103"], serve the first token, add "A104" at the end and print who is next.
Show solution
JavaScript
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(', '));
Served: A101 Next: A102 | waiting: 3 A102, A103, A104
Task 2: From prices [380, 900, 650, 500, 720], print the three most expensive without changing the original array.
Show solution
JavaScript
const prices = [380, 900, 650, 500, 720];
const top3 = [...prices].sort((a, b) => b - a).slice(0, 3);
console.log(top3, prices);
[ 900, 720, 650 ] [ 380, 900, 650, 500, 720 ]
Task 3: Remove "Ghewar" from a menu array by finding its index and using splice. What if it is not in the list?

Quick quiz

🧠 Quick Quiz – test yourself

1. ['a','b','c'][1] is…
Index starts at 0.
2. Which does NOT change the original array?
slice copies.
3. [10, 9, 1].sort() gives…
Text comparison by default.
4. const b = a; b.push(1) …
Same reference.
5. indexOf returns what for a missing value?
Check !== -1.

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.
➡️ Next

Day 7: objects – model real things (a product, an order, a student) with properties, methods, destructuring and JSON.

Frequently Asked Questions

Are arrays objects?
Yes, special objects with numeric keys and a length. typeof [] is "object"; use Array.isArray() to check.
Why did the demo use list.map(...).join("")?
map turns each item into an HTML string and join glues them – tomorrow’s and Day 8’s topics. Rendering text with innerHTML is safe here only because we will learn escaping on Day 26.
← JavaScript (30 Days)
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

Next topicDay 7: Objects, Destructuring, Spread & JSON Your progress: 6 / 30 (20%) · Lesson 7 / 30 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free