• Calls the provided callbackFn function once for each element in an array in ascending index order. It is not invoked for index properties that have been deleted or are uninitialized. And unlike the ES6 forEach() you CAN stop or break the iteration by returning -1 from the callbackFn function.

    The range (number of elements) processed by arrForEach() is set before the first call to the callbackFn. Any elements added beyond the range or elements which as assigned to indexes already processed will not be visited by the callbackFn.

    Type Parameters

    • T = any

      Identifies the element type of the array

    Parameters

    • theArray: ArrayLike<T>

      The array or array like object of elements to be searched.

    • callbackfn: ((value, index, array) => number | void)

      A synchronous function that accepts up to three arguments. arrForEach calls the callbackfn function one time for each element in the array.

        • (value, index, array): number | void
        • Parameters

          • value: T
          • index: number
          • array: T[]

          Returns number | void

    • Optional thisArg: any

      An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, null or undefined the array will be used as the this value.

    Returns void

    Remarks

    arrForEach expects a synchronous function. arrForEach does not wait for promises. Make sure you are aware of the implications while using promises (or async functions) as forEach callback.

    Example

    const items = ['item1', 'item2', 'item3'];
    const copyItems = [];

    // before using for loop
    for (let i = 0; i < items.length; i++) {
    copyItems.push(items[i]);
    }

    // before using forEach()
    items.forEach((item) => {
    copyItems.push(item);
    });

    // after
    arrForEach(items, (item) => {
    copyItems.push(item);
    // May return -1 to abort the iteration
    });

    // Also supports input as an array like object
    const items = { length: 3, 0: 'item1', 1: 'item2', 2: 'item3' };