JAVASCRIPT Tutorial

Arrays in JS

What is an Array?

An array is an ordered collection of data (elements) of various types enclosed in square brackets ([]). Elements can be accessed and manipulated using their index (position) within the array.

Key Concepts:

  • Index: Each element has an index starting from 0.
  • Length: The number of elements in the array.
  • Methods: Arrays provide methods for manipulating the elements, such as:
    • push: Add an element to the end of the array.
    • pop: Remove and return the last element.
    • shift: Remove and return the first element.
    • unshift: Add an element to the beginning of the array.
    • splice: Insert or remove elements from any position.

Example:

// Create an array
const colors = ['red', 'green', 'blue'];

// Access an element using index
console.log(colors[1]); // Output: "green"

// Add an element using push
colors.push('yellow');

// Remove an element using pop
const lastColor = colors.pop();

// Iterate over the array
for (const color of colors) {
  console.log(color);
}

Tips:

  • Arrays are mutable, meaning their contents can be changed.
  • Elements can be any type, including objects or other arrays.
  • Arrays are iterable, allowing you to use for-of loops or spread operators to iterate over their elements.