Jacob Ruiz

View Original

Mastering Javascript Fundamentals: AccountingJS Internal Helper Methods (Part 3): map()

Get the fundamentals down and the level of everything you do will rise. - Michael Jordan

As stated in my original post, I do 1 hour of video lessons from Watch and Code every day. If you're interested in learning Javascript in a way that goes beyond basic tutorials and gives you a foundational, practical knowledge without relying on frameworks - I'd highly recommend it. If you're reading these posts, please keep in mind that these are just my notes, and I'm not an expert (yet!). If your goal is also to master the fundamentals of Javascript, please head over to Watch and Code and start your journey there!

All screenshots were annotated using Shotty.


map()

Uses Array.map if it's available (ECMAScript 5 or later). If not, it falls back to its own map method.

See this content in the original post

It returns an array with the mapped results, and declares some other variables it needs for looping through.

At the end we return the results array:

However, if nativeMap exists AND the object has a native map method on it which is equal to native map, then we return the output of the native map function. So in this case the object would be an array, and we'd run the .map function on it and pass in the iterator, which is a callback function, and the context, which we knew previously as optional this.

The fallback is very simple.

It starts at i = 0

j is the object's (the array's) length:

As long as i is less than array's length, it keeps incrementing.

Then it will set the ith element in the results array to the return value of the callback function (iterator), and it will call the callback function and set the this value to the context (the optional this), and then the first argument will be the ith element in the original obj array, and then the i (the position), and then finally the actual array.

And if you're wondering where nativeMap came from, it was set earlier on line 48, where it checks to see if Array.prototype.map is available. If it is, then nativeMap will be a function, if not it will be undefined.

See this form in the original post