Muhammad Atif Akram
27 Jun 2022
•
2 min read
Perfection is achieved not when there is nothing more to add, but rather when there is nothing more to take away.
JavaScript is now the most popular and most interesting language in 21st century with lots of amazing libraries and frameworks. Majority of JavaScript engineers are familiar with standards like ES5 , ES6 etc. We daily encounter various problems in which we use various ES6 Array methods like map, filter, reduce etc.
These are really awesome smart methods to perform operations on the arrays in JavaScript. But as an engineer we should always have the knowledge and understanding how things work under the hood when we use these array methods.
Therefor, best way to understand them is to build these methods from scratch. In this article, we will build our own custom ES6 Array methods. After that, you will have a clear understanding how these methods work behind the curtain.
Lets understand everything step by step.
Handler function will act as the main function where all our business logic will go. Let's create a very simple function that just print some message and assign its reference to a variable
const es6Magic = function doES6Magic(){
console.log('Hurrah ! ES6 Custom Array Method')
}
Everything in JavaScript is inherited from the Prototype. What we target and access is basically driven through the prototypes. Think of Prototype as a the top layer and everything comes under that layer that basically access the properties from that layer. So in order to access our own custom ES6 Array Method, we must have to add it to the Array Prototype.
Array.prototype.magic = es6magic
Now we are done with everything. Let's just test it.
const numbers = [1,2,3,4, 5];
numbers.magic(); // log 'Hurrah ! ES6 Custom Array Method'`
Now, we are done with the basic overview of how ES6 Array methods works under the hood. Now, Lets jump to another real time example.
Lets build a ES6 Array method that will help us to calculate & return the factorial of each element in array.
const es6Factorial = function doES6Factorial(callback){
/* Business logic behind factorial */
function factorial(number){
if (number > 0) return number * factorial(number - 1);
return number < 0 ? -1 : 1;
}
return this.map((item) => callback(factorial(item)));
}
Array.prototype.factorial = es6Factorial;
Step 03:
const numbers = [1,2,3,4, 5];
numbers.factorial(element => console.log(element));
// 1, 4, 6, 24 , 120
I hope you enjoyed this article. Please share & thumbs up if it is really helpful for JavaScript Engineers.
Cheers :)
Muhammad Atif Akram
Software Engineer having excellent experience; a passion to write the neat & clean code to solve the complex problems but without the StackOverflow
See other articles by Muhammad
Ground Floor, Verse Building, 18 Brunswick Place, London, N1 6DZ
108 E 16th Street, New York, NY 10003
Join over 111,000 others and get access to exclusive content, job opportunities and more!