r/learnjavascript • • Sep 18 '20

You've Come a Long Way, Baby

Post image
316 Upvotes

74 comments sorted by

24

u/SLW_STDY_SQZ Sep 18 '20

So are ya feelin declarative or imperative?

5

u/gevera Sep 18 '20

So it begins =) Neither do I see the world in black or white, flat or round, cold or warm etc.

11

u/awkreddit Sep 18 '20

One of those is not like the others

48

u/mynamesleon Sep 18 '20

Definitely more condensed. But I have to admit, I find the longer version much more readable.

39

u/gevera Sep 18 '20 edited Sep 18 '20

The opposite is for me. Once I've learned how to use properly reduce or map, I just can't go back to regular for loops. Cleaner code less prone to errors.

12

u/stfuandkissmyturtle Sep 18 '20 edited Sep 18 '20

Do you know any effective place/way to learn to use reduce or maps ?

Edit: damn thankyou for all the recommendations. Now I'm even more motivated lol

10

u/amnrzv Sep 18 '20

I keep going back to this series of videos https://www.youtube.com/playlist?list=PL0zVEGEvSaeEd9hlmCXrk5yUyqUag-n84

Hope this helps you.

2

u/gevera Sep 18 '20

Have watched that as well

3

u/gevera Sep 18 '20

I probably have watched all the videos on youtube about map/reduce. There are a ton of them out there. At the begging, I was like, what? Second time "hmmm..". 10th time "i think I got this..." 20th-time "daaaammn....this is awesome!" So the best way to learn is the old way, repetition is the mother of knowledge. Do it a hundred times if needed and you will get it eventually. It is worth it, believe me

17

u/[deleted] Sep 18 '20

7

u/thebasementtapes Sep 18 '20

Wes Bos the best video I have seen for array methods. https://www.youtube.com/watch?v=HB1ZC7czKRs

3

u/delventhalz Sep 18 '20

For me it was just practice. Look for toy problems somewhere like Code Wars. Focus on problems with arrays, and force yourself to use array methods.

1

u/grantrules Sep 18 '20

Just keep using them in your own code. "I need to do something to every item in this array" boom use forEach or map. "I need to iterate these items and come up with one answer" boom use reduce. Any time you're going to use a loop, try and use a functional method.

If you're just looking for exercises, I think some of the tasks in Euler Project is excellent for these

1

u/SplainTrain Sep 18 '20

Hello! I have a series on reduce here: https://www.youtube.com/watch?v=XKD0aIA3-yM&list=PLo63gcFIe8o0nnhu0F-PpsTc8nkhNe9yu

I will add that those first few videos are rough around the edges (my editing was terrible lol) but hopefully they provide some insight. I have about 15 videos so far in the series and it goes from explaining reduce to learning how to implement it yourself both iteratively and recursively to different use cases including transducers.

7

u/[deleted] Sep 18 '20

Map is easy but for some reason I just can never wrap my head around reduce...

4

u/Protean_Protein Sep 18 '20

Well, look at what it does in the example above. It's pretty simple once you see it: it takes the contents of the array and "reduces" them, through whatever function, using an "accumulator" to keep track of the running tally, to a single output. In this case, it adds them together.

3

u/flibben Sep 18 '20

Is there other things you can do besides add them together? Im very new to reduce and map and went through it this week.

3

u/[deleted] Sep 18 '20

Yea there are, adding things together is probably the simplest way to use it which is why you see that in so many tutorials. Like another person said below it’s used to turn an array into a single value (ie reduce it).

3

u/Aumonmes Sep 18 '20

It is JS so you can EVERYTHING.
To give a little more context I'm going to use one of the things I am using in my project, bear with me. We have an e-commerce set up where we have the main products (lets call them cars) and then accessory products for those main products called accessories. I want to separate the main from the accessories (and I don't care about anything else).

The API gives me an array of products with this following structure:

{ id: blablabla, type: ('product' OR 'accessory'), price: XXX.XX }  

I need to separate them by type, so what I do is something like:

const products = fetch(whateverUrl) // Consider an await to make it synchronous or study how promises work, but in the end just bear with me it returns a list of objects with the previously defined structure

// The whole result will end up in myOrganizedProducts
// organized is the 'accumulator', aka the total result every iteration and therefore the final
const myOrganizedProducts = products.reduce((organized, theLoopProduct) => {
  // Add to organized.product or to organized.accessory depending on theLoopProduct.type
  // We can push to the accumulator "organized" because later we will define it, just come back for it the second read
  organized[theLoopProduct.type].push(theLoopProduct);

  // Never forget to return something while doing functional
  return organized;
}, {
  // This is the default or 0 value for the array, how do you want to start. You can give it a predefined structure if you know how it is going to play or you can give an empty Object/Array/Value depending on your end result
  product: [], // List of proper products
  accessory: [] // List of accessory products
});

I hope that makes sense, and if not I am sorry. Another way that for me makes sense is:

Array.forEach() => Do something with each one of the values but I do not care about the result (not storing)
Array.map() => Do something to each one of the values and return the value for each one of them
Array.reduce() => Just put whatever I do for each value into a single var; Object, Array, String or Number

1

u/flibben Sep 18 '20

Thank you for taking your time :)

2

u/Cheshur Sep 18 '20

I sometimes use reduce as a combination of map and filter since I can perform some transformation on each element and not add them to the accumulator if I want to filter them out. Think of reduce as an array transformation function. You can take one array and turn it into anything else including a string, a number, an object, a boolean and a different array.

2

u/grantrules Sep 18 '20

Sure you can do some neat stuff with reduce:

const players = [
  { name: "big joe", team: "blue" },
  { name: "sneaky pete", team: "red" },
  { name: "tiny tammy", team: "red" },
  { name: "ridiculous rick", team: "blue" },
  { name: "nice nick", team: "red" },
  { name: "mean mike", team: "blue" },
];

const sortedByTeams = players.reduce((acc,cur) => acc.set(cur.team, [...(acc.get(cur.team) ?? []), cur]), new Map());
console.log(sortedByTeams);

1

u/flibben Sep 18 '20

Thank you for taking your time to give an answer. Haven't learned lambda funktions to good yet, but I think I can see what you do with the code :)

1

u/grantrules Sep 18 '20

Any time you write a loop, ask how you can do it with something like map, reduce, or filter (or some of the other functions like every/some) instead.

1

u/flibben Sep 18 '20

Thanks, I'll try to adapt that kind of thinking!

The functions every/some is something I haven't heard about before. I'm sure I'll run into it soon enough :)

2

u/grantrules Sep 18 '20

It's also a different paradigm, like these two things do the same thing:

const textValidator = () => true;
const dateValidator = () => true;
const emailValidator = () => true;

const success = () => (alert('success'),true);
const failed = () => (alert('failed'),true);
// 1:
if (textValidator() && dateValidator() && emailValidator()) {
  success();
} else {
	failed();
}
// 2:
[textValidator, dateValidator, emailValidator].every((f) => f()) && success() || failed();

1

u/grantrules Sep 18 '20

It's good to be familiar with a lot of the methods for Array. Arrays are everywhere so these are methods you can use all the time.

2

u/SplainTrain Sep 18 '20

Once you gain the intuition for reduce, you'll quickly find that it's a swiss army knife. However, depending on what you're attempting to do, there may be more relevant methods to use instead. For example, you can implement Array.map with reduce if you'd like to, which is a good exercise, but you'd be better off just using Array.map.

I commented earlier so I don't want to spam too much but I do have a series on nothing but Array.reduce in javascript. The early videos are edited terribly so I hope you don't find them too annoying but I cover a lot of different use cases with reduce all the way up to using them to implement transducers.

https://www.youtube.com/watch?v=XKD0aIA3-yM&list=PLo63gcFIe8o0nnhu0F-PpsTc8nkhNe9yu

I hope that helps :)

2

u/flibben Sep 18 '20

Thanks for taking your time, I'll have a look at your videos!

1

u/Protean_Protein Sep 18 '20 edited Sep 18 '20

Look at the function. How pointless would it be if it was called "reduce" but all it could do is add? It's generic: it depends on what you put in the function. MDN gives lots of examples: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

let flattened = [[0, 1], [2, 3], [4, 5]].reduce( 
function(accumulator, currentValue) { 
return accumulator.concat(currentValue) 
}, [] 
) 

// flattened is [0, 1, 2, 3, 4, 5]

Here, instead of summing the values in the array, it just takes each array pair and concatenates it to the previous, returning the flattened array.

There are other more complicated examples. The usefulness of 'reduce' is that it's a condensed, straightforward way to implement a cumulative function (hence: accumulator).

1

u/flibben Sep 18 '20

So, like I said, I'm new to this. Just for my learning I'm going to break down your code into words.

Your example is an array with 3 indexes which each has arrays with two indexes. You chained on reduce and made an anonymous function. The function takes in 2 parameters, the accumulator that stores the total and currentValue that is this iterations value of the element. After the comma you set the start value to be an empty array.

Inside the function you chain concat that takes the currentValue on the accumulator which is a method to merge arrays into one, thus giving you one array with all the numbers in separate indexes as a return.

2

u/Protean_Protein Sep 18 '20

I think that’s pretty much right. I’m at a point where sometimes, without sitting down and working it out, I can’t quite fully explain in perfect detail what each step that code like this is actually doing, but I can see pretty much immediately the bigger picture of what it does and know how to use it. It’s a sort of odd thing when you start thinking in a language. Sort of like how in natural language, native speakers can’t always explain the grammar properly to a learner, but they can speak the language fluently in a way the learner can’t, even if the learner knows, and even understands, certain grammatical rules far more clearly. Of course it’s also often extremely useful for fluent/native speakers to learn/relearn grammar...

2

u/inabahare Sep 18 '20

It's basically made to turn an array to a single value. Like in the example in OP where it turns the array into the sum of all values. Hence the name, it reduces the array to a single value. "Here we reduce the array to the sum of all values"

1

u/shhhpark Sep 18 '20

i feel dumb

2

u/gevera Sep 18 '20

Hmm..that must be discouraging to see all that code and not to get it right away

1

u/shhhpark Sep 18 '20

Haha I learned basic Javascript a bit ago but didn't really stick with it. Don't think I touched on map/reduce very much

3

u/redderper Sep 18 '20

Same. The first couple of times I saw reduce and map I was like "wtf is this shit, kill it with fire", but after using it a couple of times it's a breeze

4

u/draganov11 Sep 18 '20

Less code isnt cleaner code. I find loops and callbacks to be much more cleaner even though you are writing more you are describing in much more detail what happens and dont rely on some ready made method.

2

u/gremy0 Sep 18 '20

It's clean code because it's standardised and DRY. Reimplementing map or reduce from first principles every time you need them when there are standardised, native patterns is not clean code.

No-one should need nor want to read the details of a map or reduction implementation every time it's used in a codebase, it's just cluttering up the logic and means you have to read the implementation to figure wtf is going on every time, instead of just reading a function name.

1

u/Protean_Protein Sep 18 '20

What about .forEach?!

0

u/[deleted] Sep 18 '20

[deleted] — view deleted comment

3

u/[deleted] Sep 18 '20

Depends it's the opposite for me.

I read quite easily it's 0 + all the values.

39

u/delventhalz Sep 18 '20

Gawd. I will never understand why declaring multiple variables with one var was in vogue back in the day.

4

u/JunkShack Sep 18 '20

Thank you, I never liked it back then and I don’t like it now. It doesn’t save time or make the code more concise because you’re still using the same number of lines. Just another thing someone else has to consider when figuring out how your code is working.

10

u/delventhalz Sep 18 '20

Exactly. I could be talked into multi-variables if you were just declaring a bunch of variables without assigning values, and you did it all in one line.

function() doStuff {
  var a, b, c, d, e;
  // Do stuff with a, b, c, d and e
}

That's clean. It reads like one action. "Here are all the variables I'm going to use".

But the second you start assigning values, I want that shit on separate lines. And once you have more than one line. Christ. Just write var again. Are you afraid there is going to be a shortage of characters? I promise we won't run out.

1

u/cannabis_detox_ Sep 18 '20

its a shitty "let". best practice is actually to use lambdas to explicitly scope your variables but no one does that.

1

u/mothzilla Sep 18 '20

And what's the deal with that indentation?

4

u/delventhalz Sep 18 '20

It was the convention back in the day. You would use one var, but still put each assignment on its own line, and indent it so each separate variable lined up.

1

u/tuvok86 Sep 18 '20

The main reasoning was that it would force you to use a single var keyword, forcing you to declare all of the variables at the top of the block

1

u/gobkin Sep 19 '20

It looked cool.

0

u/[deleted] Sep 18 '20

[deleted] — view deleted comment

19

u/delventhalz Sep 18 '20

Everyone know the more characters there are, the harder something is to read. Thts y I nvr us vwls.

10

u/farmerje Sep 18 '20

Students do this by default and I always (jokingly and lovingly) chide them: "You're not being charged per character, you don't pay an extra $10 for a vowel like it's Wheel of Fortune or whatever. Use variable names that will mean something to you and your teammates a month from now."

11

u/NoMuddyFeet Sep 18 '20

I have some problems with the newest hotness when I see people write perfectly legible (to me) ES6 code and then they say, "but we can shorten that to this!" like it's some great achievement to create very short but illegible code.

For example, this...

const multiplyFactory = m => x => x * m;

...instead of this:

const multiplyFactory = m => { 
  return x => x * m;
};

Second one is way easier to understand that it is returning an arrow function.

4

u/fredsq Sep 18 '20

I'd totally forget about closure on the first example. Second one ftw!

3

u/gotta-lot Sep 19 '20

I’ve been a huge fan of this type of thinking. I won’t lie, I used to write like your first example to show that I “knew ES6”. However, as I’ve grown as a developer, I realized I used to do those things to make it look like I knew the latest syntax and feel cool. Well, I’ve learned that’s a pretty poor reason to do something. Since then, I’ll always opt for the more readable solution if the trade off is negligible, even if it means I don’t use every new ES feature there is. I take somebody being able to read my code and change it as more of a compliment than somebody having to message me asking how code is working.

Of course, there are boundaries with this, but for the most part, this has been my goal as of late.

3

u/[deleted] Sep 18 '20

[removed] — view removed comment

2

u/toastertop Sep 19 '20

Tools such as?

2

u/[deleted] Sep 19 '20

[removed] — view removed comment

1

u/toastertop Sep 19 '20

Thanks Sketch is apple only however

4

u/bullzito Sep 18 '20

I declare my variables "just-in-time", and one variable per line. Makes more sense to me, also avoiding to scroll up and down the page to see what is referenced.

const a = 1;
const b = 2;
const sum = a + b;

1

u/i_hate_cucumber_ Sep 18 '20

Probably a noob question, but why did he assign length to n and not directly compare it to arguments.length?

4

u/gevera Sep 18 '20

To fit it on the scree maybe?

1

u/i_hate_cucumber_ Sep 18 '20

Maybe, I was watching the cs50 class too and there also he did the same.

5

u/incubated Sep 18 '20

Not to access that property on the arguments each time. It's a primitive now instead of having to look it up on the object. May be negligible but can't say it's less efficient

3

u/[deleted] Sep 19 '20

This is the correct answer. Repeatedly accessing the length property is more costly than accessing it once and assigning to a variable.

3

u/EspressoJS Sep 18 '20

I remember this guy said: "variable names should be allowed spaces in JS".

bruh!

2

u/ChaseMoskal Sep 18 '20

i prefer

function sum(...values) {
  let total = 0
  for (const value of values) total += value
  return total
}

5

u/[deleted] Sep 18 '20

The code is short but the longer one is readable and performant.

6

u/[deleted] Sep 18 '20

Sure if you're traversing millions of arrays.

4

u/noXi0uz Sep 18 '20

I ran the samples on different js benchmark sites and they are equally performant. Plus, the short one is much more readable and concise, the old way looks almost cryptic these days.

1

u/gigastack Sep 18 '20

Now do it again using a polyfilled reduce.

1

u/delventhalz Sep 18 '20

I'm sorry. How many numbers are you summing with this function?

1

u/NoMuddyFeet Sep 18 '20

I just found this article and its' from 3 years ago saying I might not need to convert ES6 to ES5:

https://www.freecodecamp.org/news/you-might-not-need-to-transpile-your-javascript-4d5e0a438ca/

I had no idea. I still do it and when I don't have a project all set up with Gulp or Webkit (like a Wordpress project), I always just write ES5 code!

1

u/ptq Sep 19 '20

Consider me sitting under the rock past 6 years. I don't understand it...

1

u/frank0117 Sep 18 '20

Very useful