Understanding JavaScript Arrays

Sample Image

Arrays are one of the fundamental data structures in JavaScript, used to store multiple values in a single variable. In this guide, we'll explore the basics of JavaScript arrays, including how to create, access, and manipulate them.

Creating Arrays

You can create an array in JavaScript using the array literal syntax, which consists of square brackets []. For example:

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

Accessing Array Elements

You can access individual elements in an array using square bracket notation and the index of the element. Remember, JavaScript arrays are zero-indexed, meaning the first element is at index 0. For example:

console.log(fruits[0]); // Output: 'Apple'
console.log(numbers[2]); // Output: 3

Array Methods

JavaScript arrays come with a variety of built-in methods for manipulating their contents. Some common methods include:

push(): Adds one or more elements to the end of an array.

pop(): Removes the last element from an array and returns it.

shift(): Removes the first element from an array and returns it.

unshift(): Adds one or more elements to the beginning of an array.

slice(): Returns a shallow copy of a portion of an array into a new array.

splice(): Changes the contents of an array by removing or replacing existing elements and/or adding new elements.

Iterating Over Arrays

You can iterate over the elements of an array using loops such as for loops or array methods like forEach(), map(), filter(), etc. For example:

fruits.forEach((fruit) => {
  console.log(fruit);
});

© Akshay Dinesh. All rights reserved.