r/javascript • • Mar 18 '19

What's your favorite, most useful javascript one-liner?

385 Upvotes

422 comments sorted by

View all comments

42

u/[deleted] Mar 19 '19

If you have a bunch of variables a, b, c, d, e:

console.log({ a, b, c, d, e }) to quickly log all of them as key-val pairs.

Spread operator for bypassing array methods that mutate:

const sortedArr = [...originalArr].sort()

26

u/SuperFLEB Mar 19 '19

It's useful if you only have one variable, too.

console.log({myvar})

to get the name along with the value, instead of

console.log('myvar is', myvar);

5

u/duGarbandier Mar 19 '19

My lord almighty

2

u/fgutz Mar 19 '19

oh god this is so obvious now that I feel stupid for not doing this lol

4

u/spatmonkey Mar 19 '19

I do the first one all the time, and I'll definitely be using the second one from now on.

9

u/[deleted] Mar 19 '19

Just a heads up: spread operators are generally not super quick. If you are dealing with large arrays, you may not want to do this. As with everything in software engineering, it is probably best to play it by ear ;)

8

u/[deleted] Mar 19 '19

Array.prototype.slice is a bit faster (~25%) but the spread syntax is a bit cleaner when speed doesn't matter imo. It also allows you to stick elements into your array clone really quickly and cleanly:

const leaderboard = [...highScores, userScore].sort()

5

u/[deleted] Mar 19 '19

Aw hell yea I use spread all the time. Object and array. Just wanting to spread the word about its slowness. Not an issue for probably 99% of use cases but ya never know. This is the internet after all. Also I really like your example of array spread syntax making things easy to understand!

2

u/theQuandary Mar 19 '19

You can also use console.table() instead of log for improved readability.