JavaScript Arrays

Understanding Arrays

Arrays in JavaScript are used to store multiple values in a single variable. They are one of the most useful and versatile data structures available, ideal for storing and manipulating collections of data such as lists of names, scores, or any items that can be quantified or grouped together.

An array can contain elements of any type, including numbers, strings, and even other arrays. The elements in an array are indexed, which means each item has a numbered position you can reference to access it directly.

Creating an Array

const fruits = ['Apple', 'Banana', 'Cherry'];

Accessing Array Elements

To access an element in an array, you use the index number:

console.log(fruits[1]); // Outputs: Banana

Adding Elements to an Array

You can add elements to the end of an array using the push method:

fruits.push('Orange');
    console.log(fruits); // Outputs: ['Apple', 'Banana', 'Cherry', 'Orange']

Removing Elements from an Array

Elements can be removed from an array using the pop method, which removes the last item:

fruits.pop();
    console.log(fruits); // Outputs: ['Apple', 'Banana', 'Cherry']

Looping Through Arrays

To perform operations on each item in an array, you can use a loop:

for (let i = 0; i < fruits.length; i++) {
        console.log(fruits[i]);
    }

Arrays also support a variety of other methods like map(), filter(), and reduce() that allow for more complex manipulations based on your needs.

Understanding how to effectively use arrays in JavaScript can significantly enhance your ability to handle data in your applications.

Try it Yourself

Current Array: []

Test Your Knowledge: JavaScript Arrays

What method adds an element to the end of an array?