Skip to main content

JavaScript Arrays 101

Updated 2 min readMarkdown

What arrays are and why we need them :-

Array is build in Data Structure in JavaScript that stored in contiguous memory in Storage under a single Variable name .

Why We Need Arrays

  • Group data: Store related items together.

  • Reduce variables: Avoid creating separate variables like item1, item2, and item3.

  • Clean code: Keep code organized, readable, and easier to maintain.

  • Easy looping: Allow you to efficiently step through data using loops.

Accessing elements using index

The most important feature that makes Array most usable data type is indexing for each element which starts from 0 to n-1. Where n is no of elements .

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

console.log(colors[0]); // Outputs: "red"
console.log(colors[1]); // Outputs: "green"
console.log(colors[2]); // Outputs: "blue"

Updating elements

You can update any element of the array targeting the index and reassign it value .

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

// Change "green" to "yellow"
colors[1] = "yellow"; 

console.log(colors); // Outputs: ["red", "yellow", "blue"

Array length property

The .length is the important property of the JavaScript which gives the length of the array . It updates automatically after deleting or adding elements in it .

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

console.log(colors.length); // Outputs: 3

Basic looping over arrays

Their are many methods for looping over arrays these are follows but after the ES6 their are many ways are being added like the . map() or .filter() which also return the Array .

Let go with first basic to complex .

const array = ["BJP", "Congress", "UKD", "BSP", "AYP"];

// 1st Way: Correct
for (let i = 0; i < array.length; i++) {
    console.log(array[i]);
}

// 2nd Way: Pass the current element (or index) into the arrow function
array.forEach((element) => {
    console.log(element);
});

// 3rd Way: Return a modified value for each item to create a new array
const newArray = array.map((element) => {
    return element + " Party"; 
});

// 4th Way: Fixed typo to .filter() and return a true/false condition
const filteredArray = array.filter((element) => {
    return element.length === 3; // Keeps only 3-letter names
});

No comments yet. Be the first to comment.