JavaScript Arrays


JavaScript Arrays

In this tutorial, we will learn about arrays in JavaScript. We will cover the basics of declaring and using arrays, including accessing and modifying elements.


What is an Array

An array is a collection of elements of the same type stored in contiguous memory locations. It allows you to store multiple items under a single name and access them using an index.

An array of integers

Syntax

The syntax to declare an array in JavaScript is:

let arrayName = [elements];

Working with Arrays

We will learn how to declare, initialize, access, and modify arrays in JavaScript.



Declaring and Initializing an Array

  1. Declare an integer array named arr with 5 elements.
  2. Initialize the array with values [1, 2, 3, 4, 5].
  3. Print all the elements of the array.

JavaScript Program

let arr = [1, 2, 3, 4, 5];
for (let num of arr) {
    console.log(num);
}

Output

1
2
3
4
5


Accessing Array Elements

  1. Declare an integer array named arr with 5 elements.
  2. Initialize the array with values [10, 20, 30, 40, 50].
  3. Access and print the third element of the array.

JavaScript Program

let arr = [10, 20, 30, 40, 50];
console.log('The third element is: ' + arr[2]);

Output

The third element is: 30


Modifying Array Elements

  1. Declare an integer array named arr with 5 elements.
  2. Initialize the array with values [5, 10, 15, 20, 25].
  3. Modify the second element of the array to 50.
  4. Print all the elements of the array.

JavaScript Program

let arr = [5, 10, 15, 20, 25];
arr[1] = 50;
for (let num of arr) {
    console.log(num);
}

Output

5
50
15
20
25