Js Arrays in JavaScript
? JavaScript Arrays — Overview
What is an Array?
An array is an ordered collection of values.
Arrays can hold any type of elements: numbers, strings, objects, functions, even other arrays.
Arrays are zero-indexed (first element at index 0).
Creating Arrays
const arr1 = []; // Empty arrayconst arr2 = [1, 2, 3]; // Array with numbersconst arr3 = ["apple", "banana"]; // Array with stringsconst arr4 = [1, "text", true, null];// Mixed types allowedAccessing Array Elements
const fruits = ["apple", "banana", "cherry"];console.log(fruits[0]); // "apple"console.log(fruits[2]); // "cherry"Array Properties and Methods
| Property/Method | Description | Example |
|---|---|---|
.length | Number of elements in the array | fruits.length ? 3 |
.push(item) | Add item to end | fruits.push("date") |
.pop() | Remove last item | fruits.pop() |
.shift() | Remove first item | fruits.shift() |
.unshift(item) | Add item to start | fruits.unshift("kiwi") |
.indexOf(item) | Find index of first occurrence | fruits.indexOf("banana") |
.slice(start, end) | Get a subarray (non-destructive) | fruits.slice(1, 3) |
.splice(start, deleteCount, items...) | Modify array (add/remove) | fruits.splice(1, 1, "pear") |
.forEach(callback) | Execute function for each element | fruits.forEach(f => console.log(f)) |
.map(callback) | Create new array by transforming | fruits.map(f => f.toUpperCase()) |
.filter(callback) | New array with elements passing test | fruits.filter(f => f.includes("a")) |
Example: Basic Array Usage
const numbers = [10, 20, 30, 40];// Access elementsconsole.log(numbers[1]); // 20// Add an elementnumbers.push(50);// Remove the first elementnumbers.shift();// Loop through elementsnumbers.forEach(num => console.log(num));Key Points
Arrays are mutable: you can change their contents.
Use
constto declare arrays if you don’t want to reassign the variable (but you can still modify the contents).JavaScript arrays are dynamic — you don’t need to specify size beforehand.
Want me to explain advanced topics like multidimensional arrays, array destructuring, or performance tips?