Geek Slack

Introduction to JavaScript
    About Lesson


    JavaScript Array Search


    JavaScript Array Search

    JavaScript provides several methods for searching elements within an array. These methods allow you to determine whether an element exists in an array and find its index if it does.

    1. indexOf()

    Returns the first index at which a given element can be found in the array, or -1 if it is not present.

    Example:

    const fruits = ["Apple", "Banana", "Orange", "Mango"];
    const index = fruits.indexOf("Orange");
    console.log(index); // Output: 2

    2. includes()

    Returns true if the array contains a specified element, otherwise returns false.

    Example:

    const fruits = ["Apple", "Banana", "Orange", "Mango"];
    const exists = fruits.includes("Grapes");
    console.log(exists); // Output: false

    3. find()

    Returns the value of the first element in the array that satisfies the provided testing function. Otherwise, undefined is returned.

    Example:

    const numbers = [1, 2, 3, 4, 5];
    const evenNumber = numbers.find(num => num % 2 === 0);
    console.log(evenNumber); // Output: 2

    4. findIndex()

    Returns the index of the first element in the array that satisfies the provided testing function. Otherwise, -1 is returned.

    Example:

    const numbers = [1, 2, 3, 4, 5];
    const evenIndex = numbers.findIndex(num => num % 2 === 0);
    console.log(evenIndex); // Output: 1

    These array search methods provide convenient ways to check for the presence of elements in an array and retrieve their indices or values.