Course

Introduction to Arrays

In this lesson, you'll learn about arrays in JavaScript, a fundamental data structure used to store ordered collections of elements.

Introduction

In programming, we often need an ordered collection where we have a 1st, 2nd, 3rd element, and so on. For example, we might need this to store a list of users, items, or elements.

JavaScript provides a special data structure named to store ordered collections.

Declaration

This is how we declare an array, the most important part here is the square brackets :

const months = ['January', 'February', 'March', 'April'];

Array elements are numbered, starting with zero.

Accessing Elements

We can get an element by its index using square brackets :

console.log(months[0]); // 'January'

Modifying Elements

We can replace an element:

months[2] = 'Not March'; // [ 'January', 'February', 'Not March', 'April' ]

Or add a new one to the array:

months[4] = 'May'; // [ 'January', 'February', 'Not March', 'April', 'May' ]

Array Length

The total count of the elements in the array is its :

console.log(months.length); // 5

Storing Different Types

An array can store elements of any type:

const arr = [
    'Apple',
    { name: 'John' },
    true,
    function() {
        console.log('hello');
    }
];

Looping Through Arrays

You'll often need to loop through all the elements of an array. That's where the loop comes in handy:

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

Later, we'll dedicate a few lessons to different built-in for looping. These methods allow us to loop faster, with added functionality and less code. are a powerful tool in JavaScript, enabling you to manage collections of data efficiently.

Loading...

0 Comments

"Please login to view comments"

glass-bbok

Join the Conversation!

Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.

Upgrade your account
tick-guideNext Lesson

Array Methods