📦 JavaScript Arrays
Last Updated: 12th October 2025
An array is a special variable that can hold multiple values in a single name.
Each value in an array has a position (index) starting from 0.
Hinglish Tip 🗣: Array ek aisi list hoti hai jisme hum ek hi variable me kai saari values rakh sakte hain — jaise ek dabba jisme alag-alag items hain.
✏ Creating an Array
We can create arrays in two ways:
// Using square brackets (most common)
let fruits = ["Apple", "Banana", "Mango"];
// Using new Array() constructor
let numbers = new Array(10, 20, 30, 40);
console.log(fruits);
console.log(numbers);
💡 Both ways are valid, but the square bracket [] method is preferred because it’s simple and clean.
Accessing Array Elements
We can access an array element by referring to the index number.
let colors = ["Red", "Green", "Blue"];
console.log(colors[0]); // Red
console.log(colors[1]); // Green
console.log(colors[2]); // Blue
Modifying Array Elements
We can update any value in an array using its index.
let fruits = ["Apple", "Banana", "Mango"];
fruits[1] = "Orange"; // Replace Banana with Orange
console.log(fruits); // ["Apple", "Orange", "Mango"]
🧩 Nested Arrays
Arrays can also contain other arrays inside them (multi-dimensional arrays).
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
console.log(matrix[0]); // [1, 2, 3]
console.log(matrix[1][2]); // 6
Hinglish Tip 🗣: Nested array ko 2D array bhi kehte hain — jaise Excel sheet me rows aur columns hote hain.
Array Destructuring
It means unpacking an array into multiple variables.
let fruits = ["Apple", "Banana", "Mango"];
let [a, b, c] = fruits;
console.log(a); // Apple
console.log(b); // Banana
console.log(c); // Mango
Spread with Arrays
Example 1: Copy an Array
const fruits = ["apple", "banana"];
const moreFruits = [...fruits]; // makes a copy
console.log(moreFruits);
Example 2: Merge arrays
const a = [1, 2, 3];
const b = [4, 5];
const merged = [...a, ...b];
console.log(merged);
Example 3: Flatten an Array
const array = [
[1, 2],
[3, 4],
];
const flattened = [...array[0], ...array[1]];
console.log(flattened);
Example 4: Merge Arrays with Destructuring
const a = [1, 2, 3];
const b = [4, 5];
const [c, d, ...rest] = [...a, ...b];
console.log(c); // 1
console.log(d); // 2
console.log(rest); // [3, 4, 5]
Example 5: Add New Elements to an Array
const array = [1, 2, 3];
const newArray = [...array, 4, 5];
console.log(newArray); // [1, 2, 3, 4, 5]
💡 Quick Practice
- Create an array called subjects with values ["Math", "Science", "English"].
- Print the 2nd element of the array.
- Change “English” to “Computer”.
- Exercises Set 1
- Exercises Set 2