February 28th, 2022 × #javascript#css#webdev
This vs That × map vs reduce, forEach vs for in, and more!
Wes and Scott discuss and compare JavaScript and CSS features like array methods, looping, object properties, positioning, and more.
Transcript
Announcer
Monday. Monday. Monday.
Announcer
Open wide dev fans, get ready to stuff your face with JavaScript, CSS, node modules, barbecue tips, get workflows, breakdancing, soft skill, web development, the hastiest, the craziest, the tastiest web development treats coming again hot. Here is Wes Barracuda Boss and Scott
Scott Tolinski
CSD.
Scott Tolinski
Welcome to Syntax.
Scott Tolinski
In this Monday, hasty treat. We're gonna be talking about this Versus that, in terms of JavaScript and CSS stuff where we talk about, seemingly similar features and talk a little bit about what How they're different, which ones we end up using more, and just our general thoughts on them in general. General thoughts in general. My name is Scott Talinsky. I'm a developer from Denver, Colorado. And with me, as always, is boss.
Wes Bos
Hey.
Scott Tolinski
What's up? Oh, nothing's up, man. Just hangin'. Just hangin' out.
Wes Bos
Just hangin' ready to ready to chat some this versus that. You know how it is. This verse that. I'm excited about this one, because we have often I don't know. You you often get people in web development be like, it. Reduce versus literally every other array method. Would you use? Oh, well, it's kinda like a screw versus,
Scott Tolinski
you know, I don't know. A hammer? Screw versus a nail? Yeah. Screw versus yep. Okay. Alright. Well, this episode is sponsored by 2 awesome companies, Make and Sentry. Wes, do you wanna talk about Prismic?
Wes Bos
I do. Prismic is the headless CMS for your next project. They make your website editable for the whole team. Prismic is pretty nifty. I haven't said that in a while, but this is bonafide nifty. So the way that it works Is that you just sign up for Prismic.
Wes Bos
You right away can go ahead and start creating content types.
Wes Bos
And then out the other end, you get an API. It can be a REST API. It can be a GraphQL API, but I think the special sauce that we need to focus on with Prismic here is that they have this idea of slices in that You don't go into Prismic and you can obviously make your content types. But in order to click them together for pages on your website, They have this idea of slices. So for every component that you have in your application, you can have a slice that associates it with the data that is needed in that component, and then you start clicking them together. You say, alright. I need 3 products, 2 people, Four courses. I want them all on this website, and Prismic will allow you to click together those slices. It's really cool. It's like it's like a website builder. Right? But, like, It kinda tricked me into using a website builder because I was just coding the whole time. So check it out. Prismic.i0forward/ syntax.
Wes Bos
They have all kinds of, really good starters there, whether it's for Vue or React or They've they've got it for everything. Check it out for your next project, prismic.i0forward/
Scott Tolinski
syntax. Nice. This episode is also sponsored by Century at century.i0.
Scott Tolinski
It. Use the coupon code tasty treat, all lowercase, all one word, and you'll get 2 months for free of this amazing, error exception handling service. And let me tell you, Wes, I had some I had some errors over the week over the weekend. I I woke up, put to some errors, and, You know how that can happen. I I did the whole deploy on Friday thing. You know how that, is is is not not supposed to be done, but I had a special The reason why I had to do it, I had to do the deploy, and the deploy broke some things. So I I definitely had to put in some weekend time here pawing through my Sentry it. To see the errors, how many people it was affecting, and what specifically was going down.
Scott Tolinski
It and then inspired a a syntax card for an episode I might wanna do called how to code under pressure because being, bombarded with issues or warnings or errors, it. It can be stressful, and having a tool like Sentry on your side do you have some visibility is one of the key components in my mind it. To working successfully under pressure. So thank you so much for Century for giving me the tools that I needed to be able to solve any it. The bugs or issues that I had this weekend and made my my weekend not terrible. So thank you so much for Century for sponsoring Syntex, and let's get
Sentry helps debug under pressure
Wes Bos
Into it. This or that. Yes. So the first one we have here is, when you're working with an array and you need to do something with that array, you can reach for often, you can reach for filter, map, every there's all kinds of different methods on a an array, or you can reach for reduce. And reduce is the Swiss army knife of arrays, and it can literally do Anything. So, often we hear people being like, yeah, like, reuse can do anything, but it's very hard for me to understand where, like, you get the result from the previous one. And If you don't pass it a starting value, you get the first 2 at first, and it can, like, add values together. That's often how we show reduce works, but then you can also just Modify stuff like map, but then you could filter things out like filter or you can check. So, like, what what do you possibly use? Like, what do you reach for when you need to do a bunch of stuff? Do you do you chain multiple array methods together or do you use 1 big reduce? I will chain,
Scott Tolinski
based on what I need. But you know what? I think the thing that I I always go to 1st and foremost when I'm deciding is What's the input and what's the output? Right? If my if my input is an array and the output is an array, I'm almost always reaching for map, or filter depending on what you need there. But if the input is an array and the output's an object, I'm thinking reduce. Right? You're reducing this down into something else. You're reducing the data down into, an object or even a single variable.
Preferred array methods based on input/output types
Scott Tolinski
If if I need to count something, I'm going into reduced territory. If I need to, have some data that is derived From an array of data, typically in a different form, it's going to be reduced.
Scott Tolinski
You know, the word itself, it it kind of
Wes Bos
When you're first getting into programming, you might be thinking, I don't know, reduce. What does this do? What? Yeah. But, I mean, you could think about it like in cooking. You, like, reduce something down. It. You're cooking the water off or is that what reducing does? I don't even know what reducing does. Yep. Yeah. You cook Exactly. You're you're you're you're getting rid of water. It's Usually water. That's what's boiling off, and you reduce it down into something that is generally, they would think smaller, but you reduce it into something that is different Yeah. From the Input. You're changing in state. Yeah. Yeah. And I think, like, I often will post, like, screenshots of code where I chain 3 or 4 filters and 3 or 4 maps together, and I get people being like, you could do that in one reduce. And to that, I say, That is very hard to debug because often I wanna throw a debug right in the middle. Like, okay. I'm I'm 3 steps in. I wanna see what I have, Then I'll do that. I'll just throw a debug in the middle of that. So I might refer the readability of multiple chained.
Wes Bos
And then if I need to Change what it is outputting. Like you said, if it's an object or a number or something, then you throw then I'll throw a reduce on there myself.
Wes Bos
And, usually, people cry out, oh, the performance.
Wes Bos
And, like, of course, like, if I'm my performance.
Wes Bos
Yeah. Like, for example, I, run stats on my course sales. And if I need to run stats on a year's worth of course sales, I'm not gonna be doing multiple filters maps because that is extremely process intensive. But in most cases, it's just a tiny little a array of 6 things that you need to to loop over, and there's I don't see any any hurt in that. Actually, even one step further to that example is, it. My course platform, if I wanna get stats for an entire year Mhmm. Is very slow. It's very slow. And I have to move those To MongoDB aggregation. So I need to move it out of JavaScript entirely into database size. So if you're doing anything really that heavy, then maybe needs to sit on the database, not in,
Scott Tolinski
not actually in your code. Yeah. Because the database is gonna be able to to do essentially those operations faster.
Scott Tolinski
But Exactly. Another thing there is caching too. You cache it,
Wes Bos
and you can do some heavy operations. Cash in. That's true. Yeah. If you if you have to loop over once and that value stays the same for as long as the inputs are, then you can just cache that return value and then just return it instead of actually having to loop over them. So, yeah, I'm a big fan of reduce, but I think that especially as array methods get better and even the next one for in for each, See it. I find myself using reduce less and less. It's sort of like the the last resort or like you you only use that if you need to. Like like, for example, yeah, right Now I'm selling my stickers, and I want to count how many packs are sold in US, in Canada, and in internationally.
Wes Bos
And I wanna count How many of those packs in each of those 3 categories are 1 pack, 3 pack, or 10 packs? And that's a perfect use case for reduce because I need to start with zeros all the way down and then just count them all. Yeah. Perfect. All right. The next 1 we have here is for each, Which is the array method for each, and the 4 in or 4 of.
Wes Bos
So if you want to loop over something in JavaScript, not necessarily changing it, like, reduce filter map was doing, but simply just looping over it and then doing something with each of those values. It.
forEach vs for...in loops
Wes Bos
Which one do you reach for, Scott? You know, almost always
Scott Tolinski
for each. But I I guess, You know, for me, when I I find myself looping over things, I'm almost always, like, augmenting the data or returning something. So even with these, I'm almost always reaching for map or reduce.
Scott Tolinski
It it's funny because it's like even getting into this looping territory. I don't know How many times I I do for each? I guess, I'm googling it right now. And by googling, I mean, searching it in my own repo With a fine fine, I I don't use for each that much. And I I certainly don't use Loops that much either because I I just think about the way that I program. It's like I'm always thinking I have something I need to get something else out of that. I'm gonna transform it. I'm gonna Change it. Whatever. And so for me, the the flow of creating a variable outside of a loop, doing the loop, having it be transformed in that sort of way just isn't how I find myself coding very often. So, which of these am I reaching for? Probably for each if I'm reaching for either of them.
for...in allows iterating object properties
Scott Tolinski
The only time I'm usually reaching for Any of them is using for in because it allows you to easily iterate over properties in an object.
Scott Tolinski
And so, that that's, like, the big thing for me there, in terms of, like, I I find myself needing to iterate over an object maybe sometimes more often. I reach for them
Wes Bos
probably even amount. If I'm already working with map filter, whatever, reduce, And then I need to loop over the results.
Wes Bos
Then I'll reach for 4 each and just chain it on the end there and like, all right, I got these finally things. And then for each of them, I need to Queue up some value.
Wes Bos
But more often than not, I find myself needing to do something with promises and If I need to wait for each one. So, like, let's say I can only send let let's say I want to send email to 10 people, and I don't want to Fire off all all 10 at once because because of whatever reason or if I only wanted to write to a file 1 at a time.
Wes Bos
Then I'll use the for in loop because you can await inside of a for in loop, whereas you cannot you cannot await Inside of a map filter reduce for each value at all. I didn't know you could do that. And every time I say that, someone's like, Yeah. That's I can say every time I say that someone says, oh, you you can you can use a reduce and you can return a promise that chains on the Accumulator and then use promise. Like, you can use promise dot all Mhmm. With a map and return all of Those promises and those will all fire at the exact same time. But if you need to asynchronously synchronously A go over each value 1 at a time.
Wes Bos
Then a for in is is perfect for that because you can use an await inside of there. The whole loop will pause while that value is being resolved. And then when it is resolved, you can kind of continue with your work. And it is very, very nice. There is A reduced trick you can do, but it is awful to look at, very hard to read, and it's not worth it in my opinion. A a function in our code base that's just async For each that I've been using
Scott Tolinski
since, like, since async await came out essentially to have just an async Loop like that to be able to await each step of a a four loop. So I Oh, there you go. That's interesting to me. Don't need that. Probably don't need that. Hey. That's a video that I could write. You don't need to do this thing that I'm doing.
Wes Bos
There you go.
Wes Bos
You because, like, we for It is very new. Yeah. Right? Very new. So is this single way. Right? So, I still have lots of code in my code base that's that uses, like, stuff like that because it wasn't a thing for the longest time, but now it is very easy. The other thing with, for in and for of loops is they can be stopped early.
Wes Bos
So if you need to let's say you have 100 items and you are sending out the items and then you say, okay, I found the one I needed.
Wes Bos
Then I'm gonna stop here. For whatever reason, if you need to stop the loop, and, like, grab the hammer, break the window, You can either break a loop and that loop will stop running or you can, like, skip items in a loop, which means, like, continue, Meaning that you say, okay. You know what? This item in in this loop, I'm not interested in doing any work on them, but I want to continue my work. So then I can you can just type the word continue and it will skip that iteration of the loop, but go to the next one. Most people say, oh, I'll just filter it before I loop over it. Right? That's another way to do it. That's the that's the whole reason of the show. There's many ways to do it. What did they say? There's many ways to skin a cat? Does that that's the tea?
Scott Tolinski
It is awful. Yeah. As I was saying it, I was like, I don't do I do I need to go through it saying the rest of this?
Wes Bos
Peter came out with a list of, like, like, alternatives to all of, like, you know, 2 birds, 1 stone.
Wes Bos
So there's more ways to skin. A cat is now replaced with more than one way to peel a potato. Okay. And is there, though, put all your eggs in 1 basket is put all your berries in a bowl. Okay. They're they're actually kind of, like, kind of funny and, like, it. Feed 2 birds with 1 scone. Berries in a bowl is fine, but, like, are is there more than one way to skin a potato? Yeah. There is. You could you could use a knife. You could use a potato peeler. You could throw it in a You could use a knife. A brand new knife. That's also a knife. Yeah. Let the cat out of the bag and Spell the beans.
Scott Tolinski
Okay.
Wes Bos
Take the bull by the horns is take the flower by the thorns.
Wes Bos
Yeah. That works. I like that. Be the guinea pig is be the test tube. Okay. Hold your horses as hold your phone.
Wes Bos
Open a can of worms as open Pandora's box. Bring home the bacon. Bring home the bagels. I like that.
Wes Bos
Yeah. Bring home the bagels. Be that the bring home the bagels. It's definitely it. Be to that horse's feet of fed horse. I like that. Yeah. And okay. That's it. All your eggs in 1 basket is put all your berries in 1 bowl. Okay. Well, there is more to skin
Scott Tolinski
a potato. So yeah.
Scott Tolinski
Next one is has own property, Which is a method on an object or the in keyword or has own.
hasOwnProperty vs 'in' operator
Scott Tolinski
And so I actually didn't know too much about hasOwn property versus hasOwn. So so there's there's a little bit of nuance there. But, basically, These are useful if you're checking to see if an object has a property as the name might suggest.
Scott Tolinski
If you haven't seen the in keyword before, You might have something that's like string value in object, and that's going to return a true or false. Right. That's going to be a boolean. So you could use this in a conditional to say, is this property in this object? The thing within, though, it. Is that in returns true for all inherited properties as in anything that's on the prototype, anything that's upwards on the chain. It. If there's, like the good example that they use in in Iosan MDN was that the to string method Will return true using the in keyword. So the string of to string in example Will return true where if you were to say example dot hasOwnProperty to string, it will return false Because has on property only returns true for the direct properties where the in keyword, looks up the chain of the object.
Wes Bos
Yeah. In in my beginner JavaScript course, I forget what exact example we learned when we're we're explaining this. But the the sort of the example is is when You're using, like, class based or you're extending a prototype of something like let's say you have a parent. First name, Wes, last name, Boss. And then I have my kid, Poppy.
Wes Bos
And we just give her a first name. And she inherited everything else about me.
Wes Bos
So if you were to check if Poppy has a last name, has own property, it will say no because Poppy was never assigned a last name. But if you look up the prototype chain, it will if you say, like, Poppy dot last name, it will find my name because it looks up the prototype train. And that's the difference between in. In will look up the prototype train, has own property, will not look up the prototype chain, which is often useful if you wanna see, like, Does this person have their own name, or is it just getting it from something they inherited? And then object dot has own is the exact same thing. It's just a static method, where you can pass it both an object as well as a property you wanna check for. Yeah. And so do you know about has own verse, has own property? I just said that. Yeah. No. No. I mean, like,
Scott Tolinski
like, the fact that they say to use has own pro has own as in has own Comes in as the replacement, but there's not as good of support yet for it. Oh,
Wes Bos
I don't know the difference, actually. It's it's not in all the browsers yet. So I haven't used it before. Yeah. That's kinda what I'm getting at. Is is it is it something that you think about,
Scott Tolinski
Or are you just gonna say I'm using has own property right now? Oh, it looks like there's a the problematic
Wes Bos
with has own property is that somebody could overwrite He has own property.
Wes Bos
Oh.
Wes Bos
Because JavaScript is literally anything.
Wes Bos
You could overwrite the has own property, and then you're you're pooched because how do you check For Hasown property, if you overwrote the entire functionality. Right? So the idea with static methods is that, You can just check, and I don't think you can I don't know? If you're overwriting static methods on object, then maybe you got bigger problems. But yeah.
Wes Bos
Oh, that's that's interesting. I actually had never heard of Hazone, so I'm glad you brought that to the table. Yeah.
Wes Bos
Next 1 we have here. I'm curious about what your thoughts on this is.
Position vs translate for moving elements
Wes Bos
If you are trying to skirt something around in CSS, You got to move it over up, down, left, right, a couple pixels.
Wes Bos
And we're not talking about margin here because we're not we're not Actually, reflowing the document, but we're just bumping things. You could use position absolute and then skirt it top right bottom left with With top right bottom left values. Or you could use, translate transform and translate x And go up, down, left, right.
Scott Tolinski
And I know you do a lot of animations. I'll let you take this one. Yeah. Well, the thing be even before we get into the animation thing, I think the Key thing here is that when you you're inherently giving something position absolute, you're pulling it out of the document flow entirely.
Scott Tolinski
We're like, if you're translating something, it's going to keep its space in the document, but then move it from that space.
Scott Tolinski
So you could think of it as like, it's it's it's container. Its home is still there, but the item that was inside of the home has now Moved.
Scott Tolinski
It's moved itself. So the document isn't going to reflow into that position. So it's It's important to know, like, does the document flow depend on this thing? And if it does, you know, you can use position absolute with transforms anyways. If if you're going to be animating and moving something, if you're going to be moving it over time, Every single time you want to use a translate three d, and you're gonna wanna do so, instead of doing any sort of top left animation it. Because that is it's going to give you a more performing animation. It's gonna give you closer to that 60 frames per second that You want to have in a smooth experience, but it's also just flat out what they're made for, where the position absolute left, Whatever. That's not made to be able to animate something. And I I don't know exactly why it is besides the GPU aspect of things, But it has to do with how the browser paints something and how the browser prepares for something to be able to be moved. So I I can't speak on to, like, What exactly the the paint flow? Yeah. Well, why exactly the paint flow there makes them more performant? It just is. It's what it's made for. Yeah. And that's been the case for usually Usually we always say, like, don't
Wes Bos
memorize these things, but that's probably one that you should memorize. It's been true for, like, at least 10 years now. It's just use transform if you're animating it.
Wes Bos
And like you said, like, 1 step further is positioning something absolute just to left top right left it. That's kind of annoying. Like Scott says, it gives up its its place in the document flow, and then then it's overlapping stuff. And if you do want to overlap things, and also you can use not that position absolute is bad, but there are often tools that are in CSS for the next Last 10 years that are are better than using position absolute. I think about position absolute when I want to
Scott Tolinski
actively pull something out of the flow of the document. That's when I'm reaching for a position. Absolutely. Exactly.
Scott Tolinski
Okay. We can get 1 more in here, and that's going to be, this one that I think People saw it a lot in when Redux came into Flow because you're creating a lot of new objects. So object data sign within the first parameter is an empty object, and the 2nd parameter is the object you would like to copy to create a new object based on the contents of the old object. And then there's the whole spread version of it, where it's just you create a new object and then spread the contents out of that, The object you're copying and to create a new one. So these are both methods of copying an object.
Scott Tolinski
But it's important to realize that both of these methods are just a shallow copy as in if your object is many layers deep, those many layers will remain, just references. So, that's just kind of something important to know.
Object assign vs object spread
Scott Tolinski
Do do you end up using either of these one more than they're there? I pretty much spread everything. I know I know when they've spread first dropped, people were maybe a little little like, I don't know if if this is readable.
Scott Tolinski
Yeah. What's going on here? But me, personally, I love creating a new object out of spread. And sometimes I'm just creating a new object because I'm like, well, I really want to have, confidence here that this is its own thing. This is its own object. This is a new object. Yeah. Totally. So I find myself spreading a lot. Yeah.
Wes Bos
I can't remember the last time I've used object out assigned because it only takes 2 arguments. And if you want it to have multiples or You wanna you wanna put something in the middle? Like, you're like, give me these defaults, then give me what I wanna add and then bring in what the user added. And anything that comes later will overwrite, and that that used to be a really big pain.
Wes Bos
And if I remember, I think Babbel just Took the spreads and just use object that assigned. So, feature wise, they don't they don't do anything differently, but The they're much more readable and much more flexible when you use an object spread. So I'm all about that spread. I know people people I'm angry at the spread initially because it's like like a hipster coding, like literally everywhere. People loved it, but I think it's people know what it is now. So Spread fan. Yeah. Totally. Spread fan. And you can use it you can use it with arrays as well, which is really nice. So you You don't have to, like, think, like, oh, I need to copy something. It's different if it's an object or if it's
Scott Tolinski
an array or string,
Wes Bos
right? You can sort of string. Beautiful. Well, that was fun. I I think we should ask the audience, like, send us your ideas, either if you have opinions on them or if you're just Genuinely curious. Like, why would you use one of these versus the other? More than one way to peel a potato. So we'll, we'll do another episode of this. Tweet us at Syntax FM. Yeah. So we all we could have, like, function versus arrow function.
Wes Bos
That'd be 1. Oh, yeah. There's so many. There's I just need to go it. To the like, anytime I post a screenshot of code, I need to search for why not and then find other people.
Scott Tolinski
It. That's very funny. Okay. Yes. Alright. Well, cool. We will catch you on Wednesday in our tasty treat. Thanks so much for listening.
Scott Tolinski
Peace. Peace.
Scott Tolinski
Head on over to syntax.fm for a full archive of all of our shows.
Scott Tolinski
And don't forget to subscribe in your podcast player or drop a review if you like this show.