r/learnjavascript • u/zakhorton • Jun 02 '20
14 JS Array Methods (In 8 minutes)
https://youtu.be/oN6VZGGGyP412
u/inabahare Jun 02 '20
TL;DW:
filter
map
some
every
find
forEach
reduce
includes
indexOf
lastIndexOf
sort
slice
join
toString
3
u/jaredcheeda Jun 03 '20
From a readbility standpoint reduce is a major fail. You are correct that it is powerful. But is also very badly designed and hard to intuit. Unless you are using it constantly, I would avoid it all together in favor of lower cognitive loaded alternatives.
You gave 2 examples of reduce. Let's re-write them in easier to read ways:
let stocks = [
{ name: 'Apple', price: 321.85 },
{ name: 'Tesla', price: 2471.04 },
{ name: 'Disney', price: 118.77 },
{ name: 'Google', price: 1434.87 },
{ name: 'Netflix', price: 425.92 }
];Total is the classic example of reduce, because there's no other "one-line" means of producing a total. However, number of lines has no correlation with readability.
let total = stocks.reduce(function (total, stock) {
return total + stock.price;
}, 0);
let total = 0;
stocks.forEach(function (stock) {
total = total + stock.price;
});Next is producing a flat array of strings for the names. This is an obvious abuse of reduce.
let names = stocks.reduce(function (names, stock) {
return [...names, stock.name];
}, []);map or flatMap are much better suited for this
let names = stocks.map(function (stock) {
return stock.name;
});The choices of what to cover seemed fairly haphazard. You started off with a good example and each method was almost telling a story, but towards the end it sort of got away from that concept and just seemed random. Sort sadly didn't get a very good example either. Your original array of objects would have been good to sort on name or price and show a more advanced usage of sort than just the basic flat array of strings/numbers. Which would have also given a good opportunity to show off console.table.
Note: If anyone would like to fight me on telling people to avoid reduce, just add your comment to this youtube video instead. Readability is always the most important criteria for your code.
1
u/zakhorton Jun 03 '20
(1/3)
console.table?On a spinning blue ball inhabited by intellectual - monkey looking - mammals, orbiting around a blazing ball of fire continuously enduring hydrogen powered nuclear explosions that poses the eventual end to humanity as we know it --- what drove you to
console.tableas worth while?Whatcha mean console.table!!
Lordy, lordy, lordy...I don't even -- I'm not even that religious anymore but dont know man, it feels like you need this..."dear lord sweet baby jesus above - cute and cuddly - kind and innocent - wise beyond your months, please help this soul through their journey on this spinning blue ball - they are in need of sincere love and support. Amen."If you think Imma about to start reading minds for these tutorials. my dude, although a cool console function that I personally enjoy, how would it be a "good opportunity"? For what? What would drive me to consider console.table as an opportunistic thing to show in comparison to the millions of other random oddities that happen to also be interesting and immediately accessible within chrome console?
Kevin Hart dude, you triggered a loop of Kevin hart's "what he say" skit replaying in my head (8 D)
"Wha, he said... wha...didn't catch that? Wha was that? One more time....mmm, yah missed that again.... My bad? didn't hear ya...wha?"
Alright, alright, alright -- I'm done. That one caught me a bit off guard to say the least ;)
~~~Okay, now that we're through that insanity of an expectation -- let us move on to the other points you made in your post.
You missed
slice.I forgot a two argument example of slice. Figured I'd add it for yaforEach vs. reduce ~ solid points because you are right. This is a scenario where Itook creative liberties as a content creator and ultimately teacher to booster ahighly under rated function in reduce at the expense of the most commonly usedarray function in js - and in my opinion the most over used in forEach., quiteliterally you are right.
Clean Code Studio's purpose is to teach and to provide the tools for engineers to improve. I have and will continue take creative liberties in certain regards when it comes to what I consider a positive trade off based on my personal experience.I purposely exaggerate reduce. Why Exaggerate Reduce? I do believe it is the most important javascript array method to learn. I compare it to forEach, knocking down forEach in comparison to reduce to emphasize just how important and powerful reduce is due to its sheer power in comparison to any other function. At the end of the day, javascript code in general is overall better written when a team of engineers understand the power of reduce.Trash talking forEach to uplift reduce is a calculated decision to help educate those who already know what forEach is and have never been motivated to learn the most dynamic Array method in javaScript. In real world scenarios, I would use forEach where it is simpler if for no other reason than 3 characters. Visual debt matters immensely. All of our real world application tutorials in js show this.In real world scenarios, I do find myself utilizing reduce much, much more than forEach now. Thus, I use an extreme example at the direct expense of 3 characters for every time a developer takes my emphasis on reduce literally. There are zeroother cases that come to mind where I felt it so pivotal to learn a method that Idirectly forfeit limitation of visual debt and ultimately Germane cognitive load to emphasize the importance of a point. If nothing else, that should share theimportance I put on reduce for any javascript engineer. You are right, and thereason you are calling out is an intentional example.
0
u/zakhorton Jun 03 '20
(2/2)
After watching your google podcast link I agree with everything said:
This tutorial posted above (14 array methods in 8 minutes) was created directly
after this tutorial primarily to support this tutorial 30 minutes of reduce
https://www.youtube.com/watch?v=WGleM3FeZmU
~ Grouping by nested keys
~ Array of String Formatter Callbacks That Format An Array Of Strings.
Ex: [['hello world' ,'firasd', 'asdf-asdf'], [capitalize, replaceKebab, limitLength]]
~ Reducing an array of objects, to an object where each object is keyed by a
specific element
~ Applying multiple filters within a single iteration cycle for large data sets
instead of iterating over large datasets through multiple cycles.
~ They weren't fans of functional, neither am I, but pure functions even if only
used most of the time limit the bugs in an application and allow for thorough
testing.
~ Finally, although the google engineers make solid points, they were using the
long hand version of reduce. Rarely, and I mean rarely, do I ever use the long
hand version. Between destructoring, the spread operator, the rest operator,
and implicit returns the methods shown by the googlers could be cleaned up
immensely.
~ All in all, the googlers made solid points -- many I've made my self -- but they
frankly didn't seem intimately knowledgable with reduce nor
were they using what I'll call "Functional Habits".
~ Through many, many hours working with the best JS dev I've ever known --
I grew to both dislike functional while at the same time very much
understanding it's worth and value. Personally, I used what I learned from
Alex, who frankly was difficult to work with but at the end of the day was
the most impressive engineer I've had the opportunity to learn from. He was
a physicist prior to an engineer did love functional and understood javascript at
a fundamentally different level than anyone else I've ever worked with.Very few were able to work with his code, and we had 20+ developers on our
team working at a fortune 500 company. Through trust gained in other projects
I drew the lucky/unlucky straw to go into a project he was moved off of and
finalize some code. Many, many days I would bug the hell out of him, picking his
brain trying to learn this intriquing world of functional and frankly how the hell
he was able to build what he was able to build. Machine learning face
recognition software, 3d robotic arm, Gps/Aws International localized zone
trackers (If the companies property left the zone that item belongs too, texts,
emails, sms, etc... were sent out with GPS coordinates, the distance and some
other much more NDA protected information I'm not allowed to go into.The point behind the story is this, I have ALWAYS been one to prioritize Clean
Code and readability over something like reduce. ALWAYS. Fortunately, or
unfortunately - I had the opportunity to work with one of the best functional
programmers, not only in the US but in the world.1 on 1 for months on end learning extremes about my absolute opposing
viewpoint and trust me, I didn't let his expertise keep me silent. I argued and
debated until he straight up out vetoed me in a meeting with 2 directors, 3
leads, himself and me. That veto sucked, because it meant I had to pray to god I
could understand his way of thinking in a short enough time period (2 months)
and create an entire ordering system. Long story short, he got me in that
position, he was going to teach me every damn thing he knew because the
important people upstairs were right over my shoulder and they didn't give two
damns about the fact it was functional (To be honest, they knew a little bit how
hard it was working after Alex. The degree of difficulty, they were much less
familiarized with. But they knew that many developers had tried and failed in the
past. I was moved off another high pressure project as a last resort, so the
timeline was already crunching to a close. They knew, but the stressers of
business were driving everyone to be very observant to say the least).2 months later, my mind was far from absolutely changed, but I had a new
found respect for functional programming and many of the incredible things I
learned from Alex. Here's the kicker, Alex was 29 -- and was given the very
unique privilege of not needing to show up to work until -- well, basically
whenever he felt like showing up.It was earned in a way, but at the same time it was also just insane the amount
of knowledge he brought to the team. Watching that youtube tutorial, my
immediate reaction was of course compare "Googlers" to the absolute best
Javascript engineer I have ever met. And trust me, there was no bone in my1
u/zakhorton Jun 03 '20
(3/3)
body
that wanted to say that for a long, long, LONG time. The "Googlers" sounded like
they shared a very, very similar philosophy to my own. I respect the hell out of
clean code. Readable code, Enjoyable code. I didn't get a tad of Alex's jargon,
perspective, or insights from their podcast. That to me, if nothing else, shows
they're missing the experience within the functional paradigm - even if not
advocates - to push me towards a changed perspective.Silly as it sounds, I'm looking forward to the day where I'm even closed to as
impressed by another developer as Alex. And damn, I'm hoping they preach
Clean Code because another Alex ~ well that dude is a savant. I'm hoping the
next Alex I personally meet - anyone on that level - is on that level for Clean
Code, simplification, readability, honestly non-functional mathematically proof
protected, pure function, 0 extraneous state, confusion for us meager
developers not born with Einstein level brain power and IQ scores. Because
personally, I'm a kindergarten two time taker - college drop out - who almost
failed college Algebra A ;) Thank god I fell into software and love the hell out of it.It was difficult to work after Alex, and to this day that bothers the heck out of me,
but the fact of the matter is he was able to do things no other engineer I've met -
- and I've been around a couple phenoms -- but he was the only Great. And
personal experience with him who fought tooth and nail for functional as I
fought back - frankly taught me the power of reduce. Taught me the power of
functional programming - even if not absolute functional programming. Those
googles, although I would bet extremely talented, are missing a few pieces and
could use a few lessons from Alex before knocking reduce down. Common
sense, definitely don't obliterate its usage -- unless you're learning it. If you're in
the process of learning. Use it whenever possible. That's the reason I used
reduce instead of forEach.Many, many hours working with one of the best Javascript developers in the
world taught me how deep it really goes and the js devs I used to admire are
much more like myself and most everyone else. There are very few engineers in
the world truly swimming in the ocean with the sharks, and if you're ever luck
enough for one to cross your path and frustrate the hell out of you. Just go with
it and live through a few months of hardships. It's worth it and provides an
incredible perspective.4. Number of lines has nothing to do with readability
-> Correction:
Shortened code, that directly reduces the context or semantical understanding
of the code is not improving readability.-> Even Better:
Shortening code, without losing context or semantical understanding of the
code is absolutely better than longer code with the same amount of semantical
pointers or contextual references to what the given code is doing.5 . Simplified Example Of The Example You used of The Example I used of Worst Case.
Simplified
~~~~~~~~~~
let names = stocks.map(({name}) => name);OR
let names = stocks.map(stock.name => name);Not Simplified
~~~~~~~~~~~~~
let names = stocks.map(function (stock) {return stock.name;});More Not Simplified (Maybe)?
~~~~~~~~~~~~~~~~~~let names = stocks.reduce((names, {name}) => [...names, name], []);OR
let names = stocks.reduce((names, stock) => [...names, stock.name], []);Least Simplified
~~~~~~~~~~~~~~~let names = stocks.reduce((names, stock) => {return [...names, stock.name];
}, []);6. Figured I'd match your random console.table with a random css styling of console.log :) Try it out for yourself if interested. Chrome Console Personally Tried and works (Should work in firefox as well, just haven't personally given it a goit a go).
var styles = [
'background: linear-gradient(#D33106, #571402)'
, 'border: 1px solid #3E0E02'
, 'color: white'
, 'border-radius: 3px'
, 'display: block'
, 'font-size: 18px'
, 'padding: 5px'
, 'text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3)'
, 'box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4) inset, 0 5px 3px -5px rgba(0, 0, 0, 0.5), 0 -13px 5px -10px rgba(255, 255, 255, 0.4) inset'
, 'line-height: 40px'
, 'text-align: center'
, 'font-weight: bold'
].join(';');
console.log('%c A spicy log message ?', styles);1
u/LinkifyBot Jun 03 '20
I found links in your comment that were not hyperlinked:
I did the honors for you.
delete | information | <3
1
2
3
u/fallenefc Jun 02 '20
Nice video! Very clear explaining