A collection of my 6 favorite JavaScript one-liners

learn to do more with less

Nicholas Ortenzio
4 min readFeb 20, 2014

Well, it’s Thursday, so I’m compelled to shit out another low-effort Medium post re: JavaScript development. Enjoy.

In the world of JavaScript, less code == better than. It’s the only reason that code minification is so popular these days. But even the best minifiers can never approach the efficiency, cleverness, and constant, self-loathing of the human mind. So in order to benefit you, reader, here is a compilation of useful and compact functions that I’ve used over the years.

Pad Zeros

JavaScript has terrible (nonexistent) string formatting abilities. Sometimes you want to conditionally display numbers with leading zeros, like seconds in the format of hh:mm:ss. When the minutes or seconds are less than ten, you want to see :00 and not just :0.

function pad(v){return ('0'+v).split('').reverse().splice(0,2).reverse().join('')}pad(6)  // 06
pad(13) // 13

This may be a very inefficient solution but since I birthed it from my programming womb I’m very proud of it.

Update: Patrick Denny proposes a much simpler alternate solution

 function pad(v){return ('0'+v).substr(-2);}

Get page query parameters

I originally wrote this getQueryParameters function to return the address bar query string as a key/value object. Originally it was like a twenty-line function with conditionals and error checking and shit like that. I thought I could do better.

document.location.search.replace(/(^\?)/,'').split('&').reduce(function(o,n){n=n.split('=');o[n[0]]=n[1];return o},{})

For some reason this functionality is not included in jQuery. If you want you can use this code as a for-real plugin by grabbing it from my Github repo. The plugin also lets you pass in your own query-esqe string value.

Update: Emil Pirfält noted that the built in .reduce() is functionally equivalent and more succinct.

Jenna Smith points out that if you are sure your string will always start with ?, you could replace the .replace() with .slice(1) instead.

Do more with string.replace()

Here’s a situation that will probably never occur. Let’s say you have a string that looks like this: “data-my-value.” For whatever stupid reason, you want to format it in camel case (i.e., dataMyValue). Let’s also say that the ‘my-value’ part could be any string, so we need a regular expression. An unimaginative person would simply get an array of matches and loop through them, wasting precious compute cycles. Instead, pass a function as the second argument of the replace function.

function cc(s){return s.replace(/\-(\w)/g,function(i,m){return m.toUpperCase()})} cc('data-my-value') // 'dataMyValue'
cc('html-attr') // 'htmlAttr'

Ordinals

Working as a developer for a very large and popular national sport (hint: it rhymes with dadsketball), I often have to display ranking statistics with ordinals. On the one hand, you want solve this issue as simply and elegantly as possible. On the other hand, who the fuck really cares. So you just Google the problem and copy and paste the first thing you see on stackoverflow. Which, by the way, is always from someone who’s asking for help because their code doesn’t work. A couple minutes later you realize this, scroll down the page a bit further and copy that instead.

Well, I’m here with the last solution you’ll ever need to copy and paste. (Which is just some code from stackoverflow.)

function nth(o){return o+(['st','nd','rd'][(o+'').match(/1?\d\b/)-1]||'th')}

Nested Loops

This is something I’ve written about a couple times before. Nested loops are pretty much the worst thing you can do as a programmer.

for (var i=0; i<10; i+=1) {
for (var j=0; j<10; j+=1) {
console.log(i, j);
}
}

Look at all that code. I’m so grossed out right now. A minifier isn’t going to do much to help you there. Might I present to you a better solution?

for (var i=0,j=0;i<10 && j<10;j++,i=(j==10)?i+1:i,j=(j==10)?j=0:j,console.log(i,j)){}

Destructuring Assignments

Another thing I’ve written about previously is destructuring assignments. I’m not sure what the term “destructuring assignments” even means, but I know it lets you swap two variables without the use of a temp.

// old way
c = a;
a = b;
b = c;

^^^^ sucks

// new way
[a,b] = [b,a];

Okay, I just counted, and even though it’s on one line, that’s still the same amount of non-white-space characters. Also, it doesn’t work in any browser that isn’t Firefox. So, overall, it’s not really an improvement on the original code, but it is cool-looking, so, whatever?

Array.without

This is a one line function to return an array without the first occurance of a specified value. (Which is slightly different than Array.filter())

function without (a, i){return (i=a.indexOf(i),i==-1)?a:a.slice(0,i).concat(a.slice(i+1))}

Sample usage

var arr = ['a','b','c','d','e'];
var newArray = without(arr,’c’);
// newArray = ['a','b','d','e'];

Nicholas Ortenzio is a full-time software developer who uses the word “shit” too much.

If you enjoyed this article please recommend or tweet it or just do nothing whatever I don’t care.

--

--