A diving deep into one of the most fundamental and powerful features in JavaScript: arrays. Whether you're a beginner just starting out or an experienced developer looking for a refresher, this guide will cover everything you need to know about arrays and their built-in methods. We'll explore how to create arrays, key properties, and every major method with practical, real-world examples.
Arrays are essential for handling collections of data, from simple lists to complex nested structures. By the end of this post, you'll have a solid understanding of how to manipulate arrays efficiently and idiomatically in JavaScript. Let's get started!
In JavaScript, an array is an ordered collection of values stored in a single variable. These values (called elements) can be of any type: numbers, strings, objects, functions, or even other arrays. Arrays are zero-indexed, meaning the first element is at position 0, the second at 1, and so on.
You can create arrays in a few ways:
let fruits = ["apple", "banana", "orange"]; console.log(fruits); // Output: ["apple", "banana", "orange"]
let numbers = new Array(1, 2, 3); console.log(numbers); // Output: [1, 2, 3] let emptyArray = new Array(5); // Creates an array with 5 empty slots console.log(emptyArray); // Output: [ <5 empty items> ]
let str = "hello"; let charArray = Array.from(str); console.log(charArray); // Output: ["h", "e", "l", "l", "o"]
Arrays are dynamic—they can grow or shrink as needed—and they're objects under the hood, which means they have properties and methods.
The most important property is length, which tells you how many elements are in the array and can also be used to truncate it.
let arr = [1, 2, 3, 4, 5]; console.log(arr.length); // Output: 5 arr.length = 3; // Truncates the array console.log(arr); // Output: [1, 2, 3]
JavaScript arrays come with a plethora of built-in methods. I'll categorize them for clarity: mutating (change the original array), non-mutating (return a new array or value), iteration, searching, and more. Each includes examples to illustrate usage.
These alter the array directly.
let stack = [1, 2]; stack.push(3, 4); console.log(stack); // Output: [1, 2, 3, 4]
let queue = [1, 2, 3]; let removed = queue.pop(); console.log(queue); // Output: [1, 2] console.log(removed); // Output: 3
let list = [3, 4]; list.unshift(1, 2); console.log(list); // Output: [1, 2, 3, 4]
let items = [1, 2, 3]; let firstItem = items.shift(); console.log(items); // Output: [2, 3] console.log(firstItem); // Output: 1
let months = ["Jan", "Mar", "Apr"]; months.splice(1, 0, "Feb"); // Insert at index 1 console.log(months); // Output: ["Jan", "Feb", "Mar", "Apr"] let removed = months.splice(2, 2); // Remove 2 elements from index 2 console.log(months); // Output: ["Jan", "Feb"] console.log(removed); // Output: ["Mar", "Apr"]
let unsorted = [3, 1, 4, 2]; unsorted.sort((a, b) => a - b); // Numeric sort console.log(unsorted); // Output: [1, 2, 3, 4]
let sequence = [1, 2, 3]; sequence.reverse(); console.log(sequence); // Output: [3, 2, 1]
let grid = new Array(3).fill(0); console.log(grid); // Output: [0, 0, 0]
let data = [1, 2, 3, 4, 5]; data.copyWithin(0, 3); console.log(data); // Output: [4, 5, 3, 4, 5]
These leave the original array intact.
let arr1 = [1, 2]; let arr2 = [3, 4]; let combined = arr1.concat(arr2); console.log(combined); // Output: [1, 2, 3, 4]
let full = [0, 1, 2, 3, 4]; let subset = full.slice(1, 4); console.log(subset); // Output: [1, 2, 3]
let words = ["Hello", "World"]; let sentence = words.join(" "); console.log(sentence); // Output: "Hello World"
let nums = [1000, 2000]; console.log(nums.toString()); // Output: "1000,2000" console.log(nums.toLocaleString()); // Output: "1,000,2,000" (locale-dependent)
Great for processing each element
let colors = ["red", "green", "blue"]; colors.forEach((color, index) => console.log(`${index}: ${color}`)); // Output: 0: red\n1: green\n2: blue
let scores = [10, 20, 30]; let doubled = scores.map(score => score * 2); console.log(doubled); // Output: [20, 40, 60]
let ages = [18, 21, 16, 25]; let adults = ages.filter(age => age >= 18); console.log(adults); // Output: [18, 21, 25]
let expenses = [100, 200, 300]; let total = expenses.reduce((sum, cost) => sum + cost, 0); console.log(total); // Output: 600
let path = ["home", "user", "documents"]; let fullPath = path.reduceRight((acc, dir) => dir + "/" + acc); console.log(fullPath); // Output: "documents/user/home"
let path = ["home", "user", "documents"]; let fullPath = path.reduceRight((acc, dir) => dir + "/" + acc); console.log(fullPath); // Output: "documents/user/home"
let pets = ["cat", "dog"]; console.log(pets.includes("dog")); // Output: true
let duplicates = [1, 2, 1, 3]; console.log(duplicates.indexOf(1)); // Output: 0 console.log(duplicates.lastIndexOf(1)); // Output: 2
let users = [{id: 1, name: "Alice"}, {id: 2, name: "Bob"}]; let bob = users.find(user => user.name === "Bob"); console.log(bob); // Output: {id: 2, name: "Bob"}
let values = [1, 2, 3, 2]; console.log(values.findLast(n => n === 2)); // Output: 2 console.log(values.findLastIndex(n => n === 2)); // Output: 3
let nested = [1, [2, [3]]]; console.log(nested.flat(Infinity)); // Output: [1, 2, 3]
let sentences = ["Hello world", "JavaScript rocks"]; let words = sentences.flatMap(s => s.split(" ")); console.log(words); // Output: ["Hello", "world", "JavaScript", "rocks"]
let days = ["Mon", "Tue", "Wed"]; console.log(days.at(-1)); // Output: "Wed"
let fruits = ["apple", "banana"]; for (let [index, fruit] of fruits.entries()) { console.log(`${index}: ${fruit}`); } // Output: 0: apple\n1: banana
console.log(Array.isArray([])); // Output: true let newArr = Array.of(7); // Output: [7]
Let's tie it all together with some practical scenarios.
Simulate adding, removing, and filtering tasks.
let todos = ["Buy milk", "Walk dog"]; todos.push("Pay bills"); todos = todos.filter(todo => todo !== "Walk dog"); console.log(todos); // Output: ["Buy milk", "Pay bills"]
Calculate average from an array of numbers.
let temps = [72, 68, 75, 70]; let average = temps.reduce((sum, t) => sum + t, 0) / temps.length; console.log(average); // Output: 71.25
let messy = [1, 2, 2, 3]; let unique = [...new Set(messy)]; console.log(unique); // Output: [1, 2, 3]
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions