JavaScript Arrays

Overview.

In JavaScript, an array is a collection of values or elements that can be of any data type, including other arrays. Arrays can be used to store and manipulate multiple values as a single entity.

Arrays in JavaScript are mutable, which means that you can modify, add or remove elements from them after they are created.

Array Constructor

You can create an array in JavaScript using the Array constructor function or using array literal notation.

// using Array constructor
const array1 = new Array();

// using array literal notation
const array2 = [];

You can also initialize the array with values using array literal notation.

const array3 = [1, 2, 3, 4, 5];
const array4 = ["apple", "banana", "orange"];

Accessing Array Elements

You can access elements of an array using its index, which starts from 0 for the first element.

const array = [1, 2, 3];
console.log(array[0]); // 1
console.log(array[1]); // 2
console.log(array[2]); // 3

Modifying Array Elements

You can modify the value of an element in an array by assigning a new value to it using its index.

const array = [1, 2, 3];
array[1] = 4;
console.log(array); // [1, 4, 3]

Array Methods

JavaScript provides a number of built-in methods for working with arrays.

This page was updated on -