Skip to main content
419

January 3rd, 2022 × #JavaScript#One-liners#Snippets

JS One Liners

Wes and Scott discuss handy JavaScript one-liners for common use cases like generating IDs, pausing execution, speeding up media playback, and more.

or
Topic 0 00:00

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 this web development treats coming in hot. Here is Wes Barracuda Boss and Scott

Scott Tolinski

key.

Topic 1 00:27

Intro to JavaScript one-liners

Scott Tolinski

Welcome to Syntax. In this JavaScript one liners episode of Syntax, we're gonna be talking about JavaScript one liners, little snippets and little quick little snippet, you know, you know, those things, the JavaScript one liners, the little bit of code that you can write to do a whole lot of stuff, sometimes a little bit of stuff, Sometimes they're just handy. So we're gonna be talking about some of these some of our favorite ones, some ones from Twitter, and some little things here and there. My name is Scott. I'm a developer from Denver, Colorado one with me as always is Wes Bos. Hey.

Wes Bos

We got some good one liners. This is a funny story. It's actually how I met my wife with these JavaScript one liners. So if you are, on the prowl for a partner Yep.

Wes Bos

JavaScript.

Scott Tolinski

Gonna make it work. Yeah. I'm not I mean, if they were that good, I don't I don't know how that happens.

Wes Bos

We are sponsored by Linode and Sentry. I'll talk to you about Linode real quick. And Scott could tell you about Sentry, which you can use with Linode. It's been our sponsors that you can use together. It's like a happy little happy little family.

Wes Bos

Linode is cloud computing that developers trust. They offer Linux servers that you can fire up and run. You literally run anything you want on it. You can get dedicated CPU boxes. You can get high memory boxes. You get boxes with GPU on it. You can run Kubernetes on them if you wanna, spin up a whole bunch all at once. They have load balancers and, DDoS protection. You name it. They got it. I personally run, a bunch of node applications on Linode. It's pretty sweet. You wanna check it out. Gonna give you a $100 in free credit. Go to linode.comforward/ syntax, and that's where you'll get your $100 in free credit. Thank you, Linode, for sponsoring. Thank you. This episode is also sponsored by Century at century.i0,

Scott Tolinski

the perfect place to see your errors and exceptions happen and track your performance metrics and so much more. Now Sentry is one of those, it's one of those tools that has so many tools, and it's just It's a joy to work in to use these tools and to see all of them working together.

Sponsor - Sentry

Scott Tolinski

So what you're gonna wanna do is head on over to century@century.

Scott Tolinski

IUO. Use the coupon code tasty treat, all one word, all lower case, and you'll get 2 months for free of this error and exception handling service. I'm trying to think about some of my favorite Sentry tools, maybe ones that I haven't talked about.

Scott Tolinski

There's a, a really great thing where you can tag releases inversions to your sentry.

Scott Tolinski

And that way, anytime you're pushing out a new version of your application, it's locking seeing those errors as being attached to a specific version.

Scott Tolinski

Now the thing that makes it really nice to do is be able to see, like, Alright.

Scott Tolinski

This application is this percent crash free rate.

Scott Tolinski

This version of this application Had this many crashes. This mini this version of this application had this many like, you can really track, see release over release if you are, making less mistakes over time if your team is getting better at your process, and you can evaluate your team's process just based on that release tracking stuff. It's really super neat. There's so many more tools, though. There's some user feedback tools.

Scott Tolinski

You can get alerts. You can set up alerts and maybe you're tracking a specific bug. You can see who is introducing the most bugs into your application if you'd like or Send them straight to a GitHub issue. There's so many features in Century. It's just about impossible to talk about them all. So check it out at century.i0.

Topic 3 04:02

One-liners from Twitter

Scott Tolinski

Again, coupon code tasty treat all lowercase, all one word, all one line, if I dare. So let's talk about some one liners here. Yes. I asked on Twitter and it compiled a whole bunch of my favorite one liners that I've used day to day.

Wes Bos

The code for all of these in the show notes if you wanna copy paste or just grok them. But, this should be pretty simple to do. So the first one is, For a temporary and mostly unique ID, this was in a question from one of our, podcast listeners who submitted a fake names, so we will not name them.

Wes Bos

This is when I need a temporary and mostly unique ID is, math dot random times I or sorry. 1 e fifteen.

Wes Bos

And what that is is, 1 to the power of 15, which is one with many zeros after it. Basically, math that random times whatever and then you map that floor that and that will give you a random number. And the way they say that is mostly unique is that, if you need cryptographically random numbers, you should not be using math dot random because of something.

Topic 4 05:14

Unique ID generation

Wes Bos

I'm not exactly sure why.

Wes Bos

But, if you're doing crypto or banking or anything like that that you need random numbers to be actually random, Then use the crypto

Scott Tolinski

package in node and not just math that random. Yeah. Math that I I I would imagine, though, so many of the times, you you don't need that. No. You know, you don't need something that heavy. Out of the 99% of the time, unless I'm working on authentication, I just need a a quick random number so this gets the job done.

Scott Tolinski

Next is going to be to grab a random color. Now I I've I've never used this before, but it looks like what it's doing here is it's going to generate a 6 digit code and then add in the an ampersand in front of it to turn it into a hex value. Now, Wes, is that that that's what's going on here?

Topic 5 06:03

Random color generation

Wes Bos

Yeah. This is one from, Paul Irish posted this, what, 12 years ago on his blog, and I've been using it ever since. If you need a random hex code, I'll put the link to it in the show notes here.

Wes Bos

You just take the pound not the ampersand, and then you, map that random times 167-7712.

Wes Bos

And I believe that is because that is the upper limit of what hex numbers go to.

Wes Bos

And then you 2 string it with base 16, and that will turn it into an actual hex code and not a decimal.

Scott Tolinski

It's kinda fun. If you ever need a random random color, you got it there. Yeah. That's a little that's a little fun one. A lot of these are kind of fun. Here's another one from Wes. And, actually, this is funny, Wes, that you have this one, but I I have a keyboard shortcut up to do this exact thing for me. So If you do console log and then have each property in your console log just or the sorry. The the argument of console log be an object with each of the things you're towing the log as a just a a object property, then what it does is it allows you to log those essentially with labels Because now you're logging an object with data rather than just logging a thing, which doesn't have a label. So I I have a keyboard shortcut for me. It's just command l and v s code that will take whatever string I have highlighted and turn it into a console log with the thing as a property of an object. It's super duper handy, very quick and easy. It's basically labels for your console log.

Scott Tolinski

Another thing you could do would be to Have a string of whatever you're labeling next to it, comma, the thing you're wanting to output. This is a little bit cleaner, I think. I I use this a lot because,

Topic 6 07:33

Labeled console.logs

Wes Bos

The popularity of destructuring properties into a function Yeah. Is is great. But it's sometimes annoying to log those all, because they are restructured into 3 or 4 different properties. Right? So, I use this to do that, and I found That GitHub copilot will often suggest it. If you console log and open curly bracket, it will suggest console logging all the properties of a function that are destructured, and I was very happy to see that. I do like my little

Scott Tolinski

highlight command out because it works for multiple properties too. Oh, that's awesome. Yeah. You can you post the just to that? Yeah. It's a it's actually a package, and then you just set your own keyboard shortcut to it. So I'll post the package in the show. Sweet. Yeah. I think I need that.

Topic 7 08:31

Make entire page editable

Wes Bos

Next 1 is edit anything.

Wes Bos

This is one that I often send to people who want to change something on their invoice, on my thing. They'll say, you know what? I forgot to put x, y, or z on my invoice, and I can't get it refunded unless it says this. So what I do is I tell them, open your console, paste in document dot design mode equals on.

Wes Bos

And then it will it essentially just puts content editable on the entire body and then you can literally Use your cursor and type and backspace into the entire document. The whole thing is editable when you turn this on.

Scott Tolinski

It'll be a nice little, simple little plug in too. Right? You could just have, like, a little button that hangs out in the side menu. Just click it, and then it it. I have toggles onto the whole thing.

Wes Bos

I have the, billing address content editable on because that's the thing that everybody Everybody goofs up and they wanna change, to get their invoice approved.

Wes Bos

And I'm thinking about just turning it on the entire invoice because, Like, I don't know. People shouldn't be able to fake the the price of the thing. Right? So I don't turn that on intentionally.

Wes Bos

But, Sometimes people need to change other pieces of it just to make sure it gets approved. Yeah. Yeah. I did kinda what you did there too.

Wes Bos

I kinda Go and have, like, a blank text input, and people can Yeah. Do whatever they want in there. Yeah. V a t number or whatever. Yeah. When you're when you're buying it, there's a big box that says, whatever you need on the invoice. Put it in this box, and we'll dump it onto the invoice. And, usually, it's that's the problem with worldwide. People need stuff worldwide. Yeah. Can I get my mother's maiden name on the invoice, please? Oh, that's great.

Topic 8 10:16

Get today's date with Temporal

Scott Tolinski

Next one here is I'm gonna have one that I have. This is something you may not need for a little bit here, but you know what? I I have, the temporal date. I've been messing around with the temporal API, which is the new JavaScript dates API a whole ton myself, And I thought it might be a cool to include something that could be used in the future.

Scott Tolinski

And this is basically just to get today, right now. And you can get it as sorry. I have the TypeScript in here. So I wanna let me remove the TypeScript aspects of this. So you can get the just right now by doing capitalttemporal.now.plainedateiso.

Scott Tolinski

And Then that gives you a variable in which you can do all sorts of things like today dot day, today dot month, today dot year. And it's so obvious and simple once you have that plain date because what you end up having in the temporal API is you end up having plain dates, plain date times.

Scott Tolinski

You have maybe zoned date and times, but the plain date is just right now Without a time zone, give me right now. Give me today. Here it is. So this is a nice little one. This won't work in most browsers unless you're polyfilling the temporal API, which if you're using the temporal API, you're gonna have to polyfill it. But, just just a glimpse into the future about how great it it is to just be able to say, hey, that day. Whatever. Today. Yeah. Today, that day. Next one we have here is console log inside of an implicit return. So one of the biggest pain in the butts with using,

Topic 9 11:52

Console.log in implicit return

Wes Bos

arrow function with an implicit return is that You can't pop a console log in there because it's a one liner to return.

Wes Bos

The little trick is you can console dot log the value and then say or And then continue on with the rest of your implicit return.

Wes Bos

And because console dot log will run console log your value and then console log always returns undefined.

Wes Bos

Then it will say, oh, no. And they'll fall back to the next thing.

Wes Bos

So that's just a little trick to console. I've I've mostly moved away from using implicit returns in React components because of that. Yep. I'd much rather just Have another they're free. You can have as many lines as you want. So just have an extra line with the return. You can have as as many returns as you want. And and it actually is a big thing. Like, Is there anything, like, a little bit too frustrating when, like, you have,

Scott Tolinski

some like a filter function or reduce function that's not working and then you have An implicit return in there. You're just like, oh, now I gotta put some curly brackets and whatever. So yeah. This is a nice little one because that is that is obnoxious. Versus code. Had a whole bunch of typescript refactoring

Wes Bos

things. Like, move this to another folder. Mhmm. Rename it.

Wes Bos

You know, all those refactor things in Versus code? And then Versus code moved those features to TypeScript.

Wes Bos

So it's part of the TypeScript code base, and it's something that all editors can now take advantage of.

Wes Bos

Let me let me put typescript refactor on the on the list of hasties for next year because there's some interesting stuff there. Cool. Okay. So now we're gonna get into let's see. It's the ones here. Here's one from Twitter from Matt,

Topic 10 13:32

Destructuring to remove props

Scott Tolinski

Matt MC Cherry.

Scott Tolinski

And he says to remove a prop, you can destructure And, essentially, you do const your brackets to destructure the property you would like to remove, comma, and then the rest of them is then equal to your object. This also works for a race too.

Scott Tolinski

You can do that with a race too. Here's the 1st item. Here's the tech item. Here's the rest of them. And by destructuring, using the spread operator, you're saying, like, here.

Scott Tolinski

Here's the first one. I'm now defining it as a thing, and here's the rest of them. And effectively, you're now able to have a subset of that first set, Whether that is an object, an array, whatever. I do use this one all the time. I I personally use this all the time. I I use this one to,

Wes Bos

duplicate database values. I feel like I've talked about this before, but I'll say it real quick. If you have, like, a database item has, like, their their name, their age and their weight and the an ID of that user. And you want to duplicate that person And then save it to a database. You just duplicate it, but you don't need the ID property because the ID property comes from the database. Yeah. So you can const ID, comma, dot, dot, dot, the rest. And then what that will do is it'll just take the rest of the things that were not destructured, and then you can pass that to your database save command.

Wes Bos

ESLint will yell at you because usually the prop that you removed is unused. Yeah. But who cares? Who cares? Some sometimes people put an underscore in front of it, and then they have a ESLint rule to ignore it or sign if it starts with underscore. That's what I do. 2 underscores if there's 2 unused ones. Also, like, spreading can be really useful for, like, little things like creating a new array.

Scott Tolinski

Like, I often do const new array is equal to, flat brackets old array, and then there bingo bango. You have a brand new array.

Scott Tolinski

So creating new arrays and new objects with, destructuring and spreading a. Really nice. Next one we have here is PHP style,

Wes Bos

debugging.

Topic 11 15:33

PHP-style debugging in JS

Wes Bos

So in PHP world, it's pretty common just to dump your object into the h two mile and view it there, and then stop moving it, Scott.

Wes Bos

Gosh. He's moving the tips in the in our show notes. He can't find it. There we go. I hope he's not trying to read this at this moment that I'm moving it.

Wes Bos

There is a little trick you can do as you JSON stringify, your object or array and then use, the next argument is nothing, and then the 3rd argument is a space.

Wes Bos

It will format it in a nicely indented object, and then you can dump that into a pre element. A pre element will maintain any spaces, and then it just has a nice view. I have a React component called dump. If you look on npm westboss forward slash dump, and it's exactly for that. You just wanna view the you wanna view the data as part of your application and not in your console, That's what you use. Sick. Next little trick we have here is if you wanna destructure if you wanna get the 1st and last items from an array in a single destructure.

Wes Bos

Normally when you're destructuring an array, you use square brackets. Right? But because arrays are objects, you can also use, curly brackets to destructure an array and then use the object's properties.

Topic 12 16:41

Destructure first/last array items

Wes Bos

I'm I'm using air quotes here because what properties are on an array? 0, 1, 2, 3, 4. All the properties are their indexes, And then there's 1 more property on arrays, and that's the length property. So what you can do is you can destructure 0 and rename it into first. You can destructure the length property.

Wes Bos

And then the third thing is you can destructure length minus 1 into a last variable.

Wes Bos

And that's kind of interesting. I never knew you could do this is you can use the destructured variables in the next destructured item, and you can just pull them all out at once. Kinda neat. Kinda neat.

Scott Tolinski

Here's a neat little one too for those of you who like to listen to things quickly like I do, and I know West does as well.

Scott Tolinski

You can query selector and maybe even you can query selector by any of these things, which is the audio or video element on a page. And these things, these are HTML elements. Right? If you do query document dot query selector, And then in the string property, just say video. Right? For audio comma video, whatever you're trying to to to hit. Usually, it's just 1 of the 2 of these things. Right? And you can just do dot playback rate on the element that it finds is equal to, and then it is a number value. So if you do document dot query selector, parenthesis string video string parenthesis dot playback rate is equal to 2. You're gonna set the video player on this site to be at playback rate too, and you can listen to them at what could be seen by many people as a normal speed. It's very funny. I I listen to some non tech podcasts, and somebody had, like, called into one of their, either call lines and was like, I listen to you guys at two x, And they were, like, making fun of the guy. They're, like, who would listen to a podcast at two x? It's, like, that's Come on. Like and I'm just thinking Everybody does. I feel seen right now. This is me. I do that. Yeah. I listen. I'm actually, I was at 1.8 for a long time, and I'm at 2.2. And it feels fine. Wow. Yeah. I know. That's good. Yeah. I I like overcast because you can set it per

Topic 13 17:44

Speed up audio/video

Wes Bos

per podcast. Oh, cool. Yeah. Some of the, like, more, like, storytelling ones, I'll listen a little bit slower because I'm I'm there to enjoy it not to just get the information out of it. Yeah. Totally. Technical ones like syntax all of a sudden that two acts because, I don't I like to get it through it as quick as possible and just suck the info out. Yeah. I can't wait till this podcast is over.

Scott Tolinski

I, you you then if you're in my headphones is you can get it dialed in. Yeah. It's on my headphones. I just read it up.

Topic 14 19:45

Pause execution with sleep()

Wes Bos

Next 1 we have here is sleep function.

Wes Bos

Basically, you make a variable called or a function called sleep that returns a promise, and that promise resolves After however many milliseconds you set it to, somebody submitted this and it's it's literally the same code that I have in a package called wait, w a a I t, That gets a 100,000 downloads a week.

Wes Bos

And it's just one line that basically returns a promise that resolves after however many milliseconds.

Wes Bos

And that's really handy if you just need to wait for a second or if you even need to await, 0 milliseconds and put the rest of the code at the end of the call stack because you're having issues with that. Nice. I'm going to finish up with one that, was kind

Scott Tolinski

of kind of here for us, but I'm I'm tweaking it here because there was there's was, like, very kind of specific, and this is very general. So this is that you can do if statements on one line without brackets. Now some people really hate this, so you're gonna wanna, make sure that your coding styles are kinda cool with this. But I end up using this kind of often, Especially if you have like a lot of different maybe potential cases. Maybe the match, match method that's coming will will solve some of these things, but, you know, I often do, like, if this thing, Return thing and do it all in a one liner without having any sort of brackets, without having to do that. The whole rigmarole of a bracket in a space, which I know that's gonna make some people upset, but I I do end up using this quite a bit if thing return thing. Okay. That's it.

Topic 15 21:24

If statements without brackets

Scott Tolinski

That's the liner. So, nice and simple that you do not always need curly brackets

Wes Bos

on your statements if that is part of your coding guidelines. Beautiful. So those are some cool one liners. We actually had, I don't know, 5 or 6 more. Maybe we'll save those for the next time we do this. It's always fun just to have these little one liners in your your back pocket. Not necessarily you're gonna use them. Sometimes you use them. Sometimes you they get you out of a pickle. Also, it's kinda interesting to look at it and be like, what does that do and how does that work? Because it's just like a little just little kick flip of JavaScript, you know? Yeah. Just a little kick flip. And sometimes they sometimes

Scott Tolinski

they get really obtuse with Bitwise and all sorts of who knows what's and what's it's and things you've never seen in in JavaScript. You could go on any of those lead code sites and they'll be like, alright, we want you to do this and this and this and this and this with this data, and somebody has, like, a one liner that uses, like, 8 features in JavaScript you've never seen. Those aren't always useful, but some of these nice little, nice little tidbits here. Yeah. So, welcome to 2022, And we will be catching you on Wednesday for the next episode of Syntax.

Scott Tolinski

That's all for now. Peace. Peace.

Scott Tolinski

Head on over to syntax.fm for a full archive of all of our shows, and don't forget to subscribe in your podcast player or drop a review if you like this show.

Share