JS Arrays

JavaScript Arrays: A Beginner's Guide

A JavaScript Array is a special type of variable that can hold more than one value at a time. If you have a list of items (like a list of car names or a list of numbers), storing the items in single variables could look like this:

let car1 = "Saab";
let car2 = "Volvo";
let car3 = "BMW";

This is cumbersome and not scalable. Arrays solve this problem by allowing you to store multiple values in a single reference.


1. What is an Array?

An array is an ordered collection of values. Each value is called an element, and each element has a numeric position in the array, known as its index.


2. Creating an Array

The simplest way to create an array is by using an array literal.

Array Literal Syntax (Recommended)

The array literal syntax uses square brackets [] to wrap a comma-separated list of elements.

Array Literal Example

const cars = ["Saab", "Volvo", "BMW"];
console.log(cars);

3. Accessing Array Elements

You can access an individual element in an array by referring to its index number inside square brackets.

Accessing Elements by Index

const cars = ["Saab", "Volvo", "BMW"];

// Access the first element (index 0) let firstCar = cars[0];

console.log(firstCar); // Outputs: Saab


4. Changing an Array Element

You can change the value of an element by accessing it via its index and assigning a new value.

Changing an Element

const cars = ["Saab", "Volvo", "BMW"];

// Change the first element cars[0] = "Opel";

console.log(cars); // Outputs: ["Opel", "Volvo", "BMW"]


5. The length Property

The length property of an array returns the number of elements it contains.

Array Length Property

const fruits = ["Banana", "Orange", "Apple", "Mango"];
let length = fruits.length;

console.log(length); // Outputs: 4


Exercise

?

If you have an array `const colors = ["Red", "Green", "Blue"]`, how do you access the element "Green"?