Geek Slack

Introduction to JavaScript
    About Lesson



    JavaScript Arrays


    JavaScript Arrays

    An array is a special variable that can hold multiple values under a single name. In JavaScript, arrays can hold values of different data types, and the elements are accessed using numerical indices.

    1. Creating Arrays

    Arrays can be created using array literals or the Array() constructor.

    Example:

    // Using array literal
    const fruits = ["Apple", "Banana", "Orange"];
    
    // Using Array() constructor
    const numbers = new Array(1, 2, 3, 4, 5);

    2. Accessing Array Elements

    Array elements can be accessed using numerical indices, starting from 0.

    Example:

    console.log(fruits[0]); // Output: "Apple"
    console.log(numbers[2]); // Output: 3

    3. Array Methods

    JavaScript provides several built-in methods for working with arrays, such as push(), pop(), shift(), unshift(), slice(), splice(), concat(), join(), indexOf(), and forEach().

    Example:

    // Add elements to the end of an array
    fruits.push("Grapes");
    
    // Remove the last element from an array
    fruits.pop();
    
    // Remove the first element from an array
    fruits.shift();
    
    // Add elements to the beginning of an array
    fruits.unshift("Pineapple");
    
    // Find index of an element in an array
    console.log(fruits.indexOf("Banana")); // Output: 1

    Arrays are versatile data structures in JavaScript, allowing you to store and manipulate collections of values efficiently.