10 JavaScript one-liners every developer should know

10 JavaScript one-liners every developer should know

Code should be readable and pragmatic. For me, that means when I look at a piece of code, I should almost instantly understand what it does. Clear code always has good variable names, is predictable, avoids unnecessary logic, and lives in the right place within a project.

But sometimes you need to do something a little complex without turning the rest of your code into a mess. That’s where one-liners come in. Small, pragmatic snippets that keep your code short and understandable at the same time. Here are 10 one-liners I actually use and that might save you some time too.

My top 10 one-liners

1. Sleep/delay
This one-liner is mainly used in my e2e scripts or at my mock servers. In e2e scripts, I often need to wait for certain elements to appear, like after CSS animations or after XHR calls. In mock servers, I want to simulate the potential slowness of real backend servers. It’s short, pragmatic, and that’s why it’s #1 on my list.

const sleep = ms => new Promise(r => setTimeout(r, ms));

2. Unique array values
Number two on my list is a classic. You’ve probably been asked this one-liner in a coding interview, or used it multiple times in your projects. It takes any array and returns a new one with only unique values, stripping out all duplicates.

const unique = arr => [...new Set(arr)];

3. Random number between two values
Number three on my list is a handy one-liner. You’ve probably needed this more than once when generating random numbers in your projects. It returns a random value between a given min and max, making it easy to simulate anything from dice rolls to test data. In my opinion this one-liner should be available by default as it is too basic.

const random = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;

4. Capitalize first letter
Number four on my list is a simple but handy one-liner. I usually use it when displaying database values like names. It capitalizes the first letter of a string while leaving the rest intact, making the output look clean and readable.

const capitalized = str.charAt(0).toUpperCase() + str.slice(1);

5. Variable with default value
Mostly used when I'm working with forms or (frontend) stores. A variable with a default value.

const value = input || defaultValue;

6. Detect even numbers
I have not used this one-liner in a while, I used to use this one-liner a lot when I wanted to add zebra styling to my tables and CSS did not have nth selectors yet. Yes I'm that old.

const isEven = n => n % 2 === 0;

7. Turn anything into a boolean
In conditions I prefer working with booleans, because then I don’t have to worry about truthy values being misinterpreted. To reliably turn anything into a boolean, I like to use this one-liner. It's called the double NOT operator. The first ! turns it into a logical opposite. The second one flips it again to a true or false.

const bool = !!value;

8. Debounce
Like #2, debounce is one of those questions that often pops up in tech interviews. Most developers reach for lodash or underscore.js, but you can actually write it as a one-liner. I don’t think the code is very readable, but it still earned a spot on this list, the variable name makes it clear enough. Are you unfamiliar with debounce? I wrote a blog post about debouncing with code examples

const debounce = (fn, d) => (...a) => (clearTimeout(fn.t), fn.t=setTimeout(()=>fn(...a),d));

9. Ellipsis
Although CSS can handle auto-ellipsis, this one-liner gives you full control. Instead of depending on available space, the ellipsis will always appear exactly at the nth position.

const truncate = (str, n) => str.length > n ? str.slice(0, n) + '…' : str;

10. Comparing arrays
Last but not least. Arrays are not primitives you can't use === (eqeqeq), objects (an array is an object) are compared by memory reference. Even though they look the same, there different objects in memory.

const equal = (a,b) => a.length === b.length && a.every((v,i) => v === b[i]);

Comments

There are no comments yet, leave yours below.

Leave a comment

Read more about:

The difference between debounce and throttle

Debounce and throttle are powerful techniques, but only if you really understand what they do. I often ask about them in tech interviews, and to my surprise, many developers (even seniors) struggle to explain the difference. The good news is: it’s actually quite simple. In this post, I’ll break down both techniques and share some practical use cases. If you are unfamiliar with the techniques and are asked about them too in your interview…

Continue reading

The paradox of AI in web development

Since the start of my career as a developer, I’ve seen a lot of changes. From the rise of Dreamweaver with a WYSIWYG editor for generating table code to the arrival of jQuery and professional frameworks that completely transformed web development. Nowadays, there seems to be only one buzzword everywhere: AI.…

Continue reading

The bullshit of implementing web accessibility

What is WCAG? Before I dive into the details of web accessibility, let me explain in my own words what it actually is. WCAG stands for Web Content Accessibility Guidelines. It’s a set of guidelines designed to ensure that websites and web applications are accessible to everyone, including people with disabilities…

Continue reading