In the previous tutorial, you learned how to write reusable code with functions. Now let’s talk about data. What if you need to store the names of 50 students? Will you create 50 variables? Of course not. JavaScript Arrays let you store many values in one single variable.

What is an Array?

An array is an ordered list of values. Think of it like a train: every coach has a number (starting from 0), and every coach carries one item.

Without an array:

let student1 = "Ali";
let student2 = "Sara";
let student3 = "Bilal";
let student4 = "Ayesha";

With an array:

let students = ["Ali", "Sara", "Bilal", "Ayesha"];
console.log(students);

Cleaner, shorter, and easy to loop. That is why JavaScript Arrays are used in almost every project.

1. Creating an Array

Use square brackets [ ] and separate values with commas.

let fruits = ["Apple", "Banana", "Mango"];
let numbers = [10, 20, 30, 40];
let mixed = ["Ali", 25, true, null];
let empty = [];

console.log(fruits);
console.log(numbers);
console.log(mixed);
console.log(empty);

An array can hold any data type, even a mix of types. In real projects, though, we usually keep one type in one array.

Checking if something is an array

Remember from the data types tutorial that typeof gives “object” for arrays. Use Array.isArray() to check properly:

let fruits = ["Apple", "Banana"];

console.log(typeof fruits);          // object
console.log(Array.isArray(fruits));  // true
console.log(Array.isArray("Apple")); // false

2. Accessing Array Items (Index)

Every item has an index number. The index starts from 0, not 1.

Index 0 1 2 3
Value Apple Banana Mango Orange
let fruits = ["Apple", "Banana", "Mango", "Orange"];

console.log(fruits[0]);   // Apple
console.log(fruits[2]);   // Mango
console.log(fruits[3]);   // Orange
console.log(fruits[10]);  // undefined (no such index)

Getting the first and last item

let fruits = ["Apple", "Banana", "Mango", "Orange"];

console.log(fruits[0]);                  // Apple (first)
console.log(fruits[fruits.length - 1]);  // Orange (last)
console.log(fruits.at(-1));              // Orange (modern way)

3. Array Length

The length property tells you how many items are in the array.

let fruits = ["Apple", "Banana", "Mango"];

console.log(fruits.length);  // 3

Important: the last index is always length - 1. If the length is 3, the last index is 2.

4. Changing Array Items

Use the index to replace any value.

let fruits = ["Apple", "Banana", "Mango"];

fruits[1] = "Grapes";

console.log(fruits);  // ["Apple", "Grapes", "Mango"]

Wait, we used const or let? Here is a useful fact. If you declare an array with const, you can still change its items, but you cannot assign a completely new array to that variable:

const colors = ["red", "green"];

colors[0] = "blue";        // allowed
colors.push("yellow");     // allowed
console.log(colors);       // ["blue", "green", "yellow"]

colors = ["black"];        // Error: Assignment to constant variable

5. Adding and Removing Items

These 4 methods are the most important JavaScript Arrays methods for beginners.

Method What it does Where
push() Adds an item At the end
pop() Removes an item From the end
unshift() Adds an item At the start
shift() Removes an item From the start
let fruits = ["Apple", "Banana"];

// push: add at the end
fruits.push("Mango");
console.log(fruits);   // ["Apple", "Banana", "Mango"]

// pop: remove from the end
let removed = fruits.pop();
console.log(removed);  // Mango
console.log(fruits);   // ["Apple", "Banana"]

// unshift: add at the start
fruits.unshift("Orange");
console.log(fruits);   // ["Orange", "Apple", "Banana"]

// shift: remove from the start
fruits.shift();
console.log(fruits);   // ["Apple", "Banana"]

Easy trick to remember: push/pop work at the end, unshift/shift work at the start.

6. Looping Through Arrays

You learned loops already. Now combine them with JavaScript Arrays.

let students = ["Ali", "Sara", "Bilal", "Ayesha"];

// Method 1: normal for loop (when you need the index)
for (let i = 0; i < students.length; i++) {
  console.log((i + 1) + ". " + students[i]);
}

// Method 2: for...of (when you only need values)
for (let student of students) {
  console.log(student);
}

// Method 3: forEach
students.forEach(function (student, index) {
  console.log(index + ": " + student);
});

7. Searching in an Array

let fruits = ["Apple", "Banana", "Mango", "Banana"];

// includes: true or false
console.log(fruits.includes("Mango"));   // true
console.log(fruits.includes("Grapes"));  // false

// indexOf: position of first match, -1 if not found
console.log(fruits.indexOf("Banana"));   // 1
console.log(fruits.indexOf("Grapes"));   // -1

// lastIndexOf: position of last match
console.log(fruits.lastIndexOf("Banana")); // 3

// Real use: check before adding
let item = "Grapes";
if (!fruits.includes(item)) {
  fruits.push(item);
}
console.log(fruits);

8. Joining, Combining and Reversing

let fruits = ["Apple", "Banana", "Mango"];

// join: array to string
console.log(fruits.join(", "));   // Apple, Banana, Mango
console.log(fruits.join(" - "));  // Apple - Banana - Mango

// concat: combine two arrays
let fruits2 = ["Orange", "Grapes"];
let allFruits = fruits.concat(fruits2);
console.log(allFruits);  // ["Apple", "Banana", "Mango", "Orange", "Grapes"]

// reverse: reverse the order (changes the original array)
let numbers = [1, 2, 3, 4];
numbers.reverse();
console.log(numbers);    // [4, 3, 2, 1]

// split: string to array (opposite of join)
let text = "HTML,CSS,JavaScript";
let courses = text.split(",");
console.log(courses);    // ["HTML", "CSS", "JavaScript"]

9. Slice and Splice

These two names look similar, but they do different things.

slice(): copy a part (original stays safe)

let fruits = ["Apple", "Banana", "Mango", "Orange", "Grapes"];

// slice(start, end) - end is NOT included
console.log(fruits.slice(1, 3));  // ["Banana", "Mango"]
console.log(fruits.slice(2));     // ["Mango", "Orange", "Grapes"]
console.log(fruits.slice(-2));    // ["Orange", "Grapes"]

console.log(fruits);  // original is unchanged

splice(): add or remove items (original changes)

let colors = ["red", "green", "blue", "yellow"];

// splice(startIndex, deleteCount)
let removed = colors.splice(1, 2);
console.log(removed);  // ["green", "blue"]
console.log(colors);   // ["red", "yellow"]

// splice(startIndex, 0, newItem) - insert without deleting
colors.splice(1, 0, "pink");
console.log(colors);   // ["red", "pink", "yellow"]

// splice(startIndex, 1, newItem) - replace one item
colors.splice(0, 1, "black");
console.log(colors);   // ["black", "pink", "yellow"]

Easy memory trick: slice only takes a copy, splice actually cuts the original array.

10. Sorting Arrays

let names = ["Sara", "Ali", "Bilal", "Ayesha"];
names.sort();
console.log(names);  // ["Ali", "Ayesha", "Bilal", "Sara"]

Be careful with numbers. By default, sort() treats everything as text:

let numbers = [10, 5, 100, 25];

numbers.sort();
console.log(numbers);  // [10, 100, 25, 5]  (wrong order for numbers!)

// Correct way for numbers
numbers.sort(function (a, b) {
  return a - b;
});
console.log(numbers);  // [5, 10, 25, 100]  (small to big)

// Big to small
numbers.sort((a, b) => b - a);
console.log(numbers);  // [100, 25, 10, 5]

11. Copying an Array (Important!)

Arrays are reference types, as we learned in the data types tutorial. If you simply assign one array to another variable, both point to the same data.

let list1 = [1, 2, 3];
let list2 = list1;     // NOT a real copy

list2.push(4);

console.log(list1);    // [1, 2, 3, 4]  (original also changed!)
console.log(list2);    // [1, 2, 3, 4]

To make a real, independent copy:

let list1 = [1, 2, 3];

let copy1 = list1.slice();      // way 1
let copy2 = [...list1];         // way 2 (spread, we will learn it in ES6)

copy1.push(4);
copy2.push(5);

console.log(list1);  // [1, 2, 3]  (safe)
console.log(copy1);  // [1, 2, 3, 4]
console.log(copy2);  // [1, 2, 3, 5]

12. Array of Arrays (2D Array)

An array can contain other arrays. This is useful for tables and grids.

let marks = [
  [80, 70, 90],
  [60, 85, 75],
  [95, 88, 92]
];

console.log(marks[0]);      // [80, 70, 90]
console.log(marks[1][2]);   // 75 (row 1, column 2)

// Loop through all values
for (let row = 0; row < marks.length; row++) {
  for (let col = 0; col < marks[row].length; col++) {
    console.log("Row " + row + ", Col " + col + ": " + marks[row][col]);
  }
}

13. Array of Objects (Very Common in Real Projects)

In real applications, data usually comes as an array of objects, for example a list of users or products.

let products = [
  { name: "Laptop", price: 85000 },
  { name: "Mouse", price: 1200 },
  { name: "Keyboard", price: 3500 }
];

console.log(products[0].name);    // Laptop
console.log(products[2].price);   // 3500

for (let product of products) {
  console.log(product.name + " costs Rs. " + product.price);
}

Practical Example 1: Total and Average

let marks = [78, 92, 45, 66, 88];
let total = 0;

for (let mark of marks) {
  total += mark;
}

let average = total / marks.length;

console.log("Total: " + total);       // Total: 369
console.log("Average: " + average);   // Average: 73.8

Practical Example 2: Find Highest and Lowest

let numbers = [34, 78, 12, 95, 47];

let highest = numbers[0];
let lowest = numbers[0];

for (let num of numbers) {
  if (num > highest) {
    highest = num;
  }
  if (num < lowest) {
    lowest = num;
  }
}

console.log("Highest: " + highest);  // 95
console.log("Lowest: " + lowest);    // 12

Practical Example 3: To-Do List

let todoList = [];

function addTask(task) {
  todoList.push(task);
  console.log("Added: " + task);
}

function removeTask(task) {
  let index = todoList.indexOf(task);
  if (index !== -1) {
    todoList.splice(index, 1);
    console.log("Removed: " + task);
  } else {
    console.log("Task not found");
  }
}

function showTasks() {
  console.log("--- My Tasks ---");
  for (let i = 0; i < todoList.length; i++) {
    console.log((i + 1) + ". " + todoList[i]);
  }
}

addTask("Learn JavaScript Arrays");
addTask("Practice loops");
addTask("Build a project");
removeTask("Practice loops");
showTasks();

// Output:
// Added: Learn JavaScript Arrays
// Added: Practice loops
// Added: Build a project
// Removed: Practice loops
// --- My Tasks ---
// 1. Learn JavaScript Arrays
// 2. Build a project

Practical Example 4: Remove Duplicates

let numbers = [1, 2, 2, 3, 4, 4, 5];
let unique = [];

for (let num of numbers) {
  if (!unique.includes(num)) {
    unique.push(num);
  }
}

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

Practical Example 5: Show Array on a Webpage

<ul id="students"></ul>

<script>
  let students = ["Ali", "Sara", "Bilal", "Ayesha"];
  let html = "";

  for (let student of students) {
    html += "<li>" + student + "</li>";
  }

  document.getElementById("students").innerHTML = html;
</script>

Do not worry about document.getElementById yet. We will learn the DOM later in this series.

Common Mistakes to Avoid

let fruits = ["Apple", "Banana", "Mango"];

// Mistake 1: thinking index starts from 1
console.log(fruits[1]);   // Banana (not Apple!)

// Mistake 2: off-by-one in loops
// for (let i = 0; i <= fruits.length; i++)   WRONG: last round gives undefined
for (let i = 0; i < fruits.length; i++) {      // CORRECT
  console.log(fruits[i]);
}

// Mistake 3: using = to copy an array (it shares the same data)
let copy = fruits;           // WRONG
let realCopy = [...fruits];  // CORRECT

// Mistake 4: sorting numbers without a compare function
// [10, 9, 100].sort()  gives [10, 100, 9]

Quick Recap

  • An array stores many values in one variable: ["a", "b", "c"]
  • Index starts from 0, and the last index is length - 1
  • push/pop work at the end, unshift/shift work at the start
  • includes and indexOf search for values
  • slice copies a part, splice adds or removes in the original
  • sort() needs a compare function for numbers
  • Arrays are reference types, so use slice() or [...arr] to copy

Great job! You now know how JavaScript Arrays work. Arrays and loops together are the heart of data handling in every real application.

Practice Exercises

  1. Create an array of 5 of your favorite foods and print the first and last item.
  2. Add one more food at the end and one at the start. Print the array and its length.
  3. Remove the last and the first item. Print the array again.
  4. Print all items with numbers like “1. Pizza”, “2. Biryani” using a loop.
  5. Check if “Pizza” exists in your array using includes().
  6. Create an array of 6 numbers. Print the sum of all numbers and the sum of only the even numbers.
  7. Sort an array of numbers from big to small.
  8. Create an array [1, 2, 3, 4, 5] and use slice() to get [2, 3, 4].
  9. Reverse an array without using the reverse() method (use a loop).
  10. Create an array of 3 products (objects with name and price) and print the total price.

Assignment

Build a Student Records Manager:

  1. Create two arrays: names = ["Ali", "Sara", "Bilal", "Ayesha", "Usman"] and marks = [78, 92, 45, 66, 88].
  2. Print each student with their marks, like: 1. Ali - 78
  3. Calculate and print the total and average marks.
  4. Find the student with the highest marks and print their name.
  5. Create a new array passedStudents and use a loop to add the names of all students who scored 50 or more.
  6. Add a new student “Hina” with 71 marks to both arrays using push().
  7. Print the final report.

Expected output for steps 3 to 5:

Total: 369
Average: 73.8
Top Student: Sara (92)
Passed: Ali, Sara, Ayesha, Usman

Bonus Challenge

Create a function removeDuplicates(arr) that returns a new array without duplicate values. Then create another function findSecondLargest(arr) that returns the second largest number from an array (without using sort()). Test both with several arrays.

What’s Next?

In the next tutorial, we will learn JavaScript Objects. Objects store data as key-value pairs (like name: “Ali”), and together with JavaScript Arrays they let you handle real-world data like users, products and orders.

Missed the last tutorial? Go back to JavaScript Functions, or browse the full JavaScript Tutorial Series. For deeper reference, see the MDN Array reference.

About Author

Arshad Sultan

Arshad Sultan is the Founder of Tutorials Ocean and a Technical Architect & Full-Stack Developer with 15+ years of experience in PHP, Laravel, CRM development, API integrations, and AI-powered automation. He also runs Rapid Code, a software and AI automation agency, and has trained hundreds of students across Karachi's IT institutes since 2010.

Leave a Reply

Your email address will not be published. Required fields are marked *