OnlineCBT Logo OnlineCBT
JavaScript Tutorial
JAVASCRIPT · LESSON 12

Arrays: Creation, Indexing, and Mutating Methods

By Ratan Updated: 16 Oct 2026

Store ordered lists and manipulate elements using push, pop, shift, unshift, splice, and slice.

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

Keep an ordered collection and understand mutation

An array stores indexed elements and has a length property. Indexing starts at zero. Several familiar methods modify the original array, so know whether a method changes data before sharing that array with other code.

const lessons = ['Variables', 'Loops'];
lessons.push('Functions');
console.log(lessons.length); // 3
console.log(lessons[0]); // Variables
const removed = lessons.pop();
console.log(removed); // Functions
lessons.unshift('Introduction');
console.log(lessons); // ['Introduction', 'Variables', 'Loops']

push/pop work at the end. unshift/shift work at the beginning. Their return values differ: push returns the new length, while pop returns the removed element.

splice versus slice

const marks = [10, 20, 30, 40];
const copy = marks.slice(1, 3);
console.log(copy); // [20, 30]
marks.splice(1, 2, 25);
console.log(marks); // [10, 25, 40]

slice returns a shallow portion and leaves the original array's sequence unchanged. splice removes/inserts in the original. The second splice argument is a removal count, not an end index.

Numeric sorting

const values = [2, 10, 3];
values.sort((a, b) => a - b);
console.log(values); // [2, 3, 10]

Without a comparator, sort uses string-based ordering and can place 10 before 2. sort and reverse mutate the array. If you need to preserve it, copy first or use a supported nonmutating alternative appropriate to the project's runtime.

Shallow copies and holes

Copying an array does not deeply clone object elements. Both arrays can still reference the same student object. Assigning to an index far beyond length creates empty slots; empty slots are not identical in every array operation to explicit undefined values. Prefer sequential construction over sparse arrays for ordinary lesson lists.

Practice

  1. Remove the first item and inspect shift's returned value.
  2. Delete one middle lesson with splice.
  3. Sort a copied marks array and confirm the original order remains.
  4. Predict reading index equal to length: normally undefined, not the final element.

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
पता संपर्क करें

+91 7877547686

ई-मेल

onlinecbtportal@gmail.com

हेल्पलाइन नंबर

+91 7877547686


डाउनलोड करने के लिए क्लिक करें
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat