JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

JavaScript Arrays

8 April 2025 | Category:

An Array is a special variable in JavaScript that can store multiple values in a single variable.

Instead of creating separate variables for each value:

let item1 = "Apple";
let item2 = "Banana";
let item3 = "Mango";

You can use an array:

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

✅ How to Create an Array

1. Using Square Brackets [] (Recommended)

let cars = ["BMW", "Audi", "Mercedes"];

2. Using new Array() (Not recommended)

let bikes = new Array("Yamaha", "Suzuki", "Kawasaki");

✅ Accessing Array Elements

Array elements are accessed using their index (starts from 0):

let colors = ["Red", "Green", "Blue"];

console.log(colors[0]); // Red
console.log(colors[1]); // Green
console.log(colors[2]); // Blue

✅ Array Length

Use .length to get the total number of items in the array:

let items = ["Pen", "Pencil", "Eraser"];
console.log(items.length); // 3

✅ Modifying Arrays

Change a value:

let fruits = ["Apple", "Banana", "Mango"];
fruits[1] = "Orange";
console.log(fruits); // ["Apple", "Orange", "Mango"]

Add new item:

fruits[3] = "Grapes";

✅ Common Array Methods

MethodDescriptionExample
push()Adds element to the endarr.push("item")
pop()Removes last elementarr.pop()
shift()Removes first elementarr.shift()
unshift()Adds element to the beginningarr.unshift("item")
lengthReturns the number of elementsarr.length
indexOf()Finds index of an itemarr.indexOf("Apple")
includes()Checks if array contains a valuearr.includes("Mango")
join()Converts array to stringarr.join(", ")
slice()Extracts part of the arrayarr.slice(1, 3)
splice()Add/remove elementsarr.splice(2, 0, "item")
reverse()Reverses array orderarr.reverse()
sort()Sorts array alphabetically (or numerically)arr.sort()

✅ Looping Through an Array

Using for loop:

let fruits = ["Apple", "Banana", "Mango"];
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

Using forEach():

fruits.forEach(function(item) {
  console.log(item);
});

✅ Arrays Can Store Different Types

JavaScript arrays can store strings, numbers, objects, even other arrays.

let mix = ["Hello", 42, true, { name: "John" }, [1, 2, 3]];

⚠️ Note: JavaScript Arrays are Objects

Arrays in JavaScript are technically objects, but they have special methods and behavior.

typeof ["Apple", "Banana"]; // "object"

✅ Summary

  • Arrays store multiple values in a single variable.
  • Array elements are accessed by index.
  • JavaScript provides many built-in methods to work with arrays.
  • Arrays can store different data types.