Array in Javascript

Javascript

Arrays serve as powerful data structures, allowing you to store and organize multiple values under a single variable name. Whether it’s a list of numbers, strings, or a combination of both, arrays provide a convenient way to manage and manipulate data efficiently.

Creating an Array

  1. Array Literal

    Creating an array in JavaScript is straightforward. You can initialize an array by enclosing its elements within square brackets:

    let myArray = [1, 2, 3, 4, 5];
    
  2. Using the New Keyword

    Another way to create an array is by using the new keyword along with the Array constructor. This method initializes a new array object.

    // Creating an array using the new keyword
    let myArray = new Array(1, 2, 3, 4, 5);
    

Accessing Array Elements

Accessing individual elements within an array is crucial. This is achieved by referencing the index of the element. Remember, JavaScript arrays are zero-indexed, meaning the first element is at index 0.

let firstElement = myArray[0]; // Retrieves the first element (1)
let secondElement = myArray[1]; // Retrieves the second element (2)

Changing an Array Element

Arrays are mutable, meaning you can change their elements after creation. To modify a specific element, assign a new value to the desired index:

myArray[2] = 10; // Changes the third element to 10

Looping Array Elements

Iterating through array elements is often necessary. A common method to achieve this is by using a for loop:

for (let i = 0; i < myArray.length; i++) {
    console.log(myArray[i]); // Outputs each element in the array
}

Here’s a simpler JavaScript program that demonstrates the basic concepts of arrays:

// Creating an array of fruits
let fruits = ["Apple", "Banana", "Orange", "Grapes"];

// Displaying the elements in the array
console.log("Fruits in the array:");
for (let i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}

// Accessing and displaying the first fruit
let firstFruit = fruits[0];
console.log("The first fruit is:", firstFruit);

// Changing the second fruit
fruits[1] = "Kiwi";

// Displaying the array after the modification
console.log("Array after changing Banana to Kiwi:");
for (let i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}

Array Elements Can Be Objects

Array elements can be more than just simple values; they can be objects. This flexibility allows for the creation of complex data structures.

let studentArray = [
    { name: 'Alice', age: 20 },
    { name: 'Bob', age: 22 },
];