Native Implementation

ForEach

// Some code
/*******************************************************************************
Write a function `myForEach` that accepts an array and a callback as arguments.
The function should call the callback on each element of the array, passing in the
element, index, and array itself. The function does not need to return any value.

Do not use the built in Array#forEach.

Examples:

myForEach(['a', 'b', 'c'], function (el, i) {
    console.log(el + ' is at index ' + i);
}); // prints
// a is at index 0
// b is at index 1
// c is at index 2

let test = [];
myForEach(['laika', 'belka'], function (el) {
    test.push(el.toUpperCase());
});
console.log(test); // ['LAIKA', 'BELKA']
*******************************************************************************/

function myForEach(array, cb) {
    for (let i = 0; i < array.length; i++) {
        let el = array[i];
        cb(el, i, array);
    }
}


module.exports = myForEach;

Map

Reduce

Array Callback Methods Implemented With For Loops

How to implement array callback methods in JavaScript


Array Callback Methods Implemented With For Loops

How to implement array callback methods in JavaScript

Functions are called โ€œFirst Class Objectsโ€ in JavaScript because:

  • A function is an instance of the Object type

  • A function can have properties and has a link back to its constructor method

  • You can store the function in a variable

  • You can pass the function as a parameter to another function

  • You can return the function from a function

What do you think will be printed in the following:

Anonymous callback, a named callback

Function that takes in a value and two callbacks. The function should return the result of the callback whoโ€™s invocation results in a larger value.

Note: we do not invoke negate or addOne (by using () to call them), we are passing the function itself.

Write a function, myMap, that takes in an array and a callback as arguments. The function should mimic the behavior of Array.prototype.map.

Write a function, myFilter, that takes in an array and a callback as arguments. The function should mimic the behavior of Array.prototype.filter.

Write a function, myEvery, that takes in an array and a callback as arguments. The function should mimic the behavior of Array.prototype.every.

Further Examples of the above concepts

Last updated

Was this helpful?