DEV Community

loading...
Cover image for 20 JavaScript One-Liners That Will Help You Code Like a Pro

20 JavaScript One-Liners That Will Help You Code Like a Pro

ovi profile image Muhammad Ovi Originally published at muhammadovi.com ・5 min read

JavaScript keeps growing and growing, opening doors for new
"to be tech geeks" in the market as it's one of the easiest languages to start. (is it really?)

It's true that JavaScript can do a lot of blazing things! and there is just so much to learn.

And whether you’re new to JavaScript or more of a professional developer it’s always good to learn something new.

I'm gonna go over some really helpful one-liners (20 + Bonus) that can help you boost your productivity and can help in debugging code.


What is a one-liner actually?

A one-liner is a code practice in which we perform some function in just one line of code.


01 - Get a random boolean

This function will return a boolean (true or false) using Math.random() method.
Math.random creates a random number between 0 and 1, after which we check if it is higher or lower than 0.5.
That means it's a 50/50 chance to get either true or false.

const getRandomBoolean = () => Math.random() >= 0.5;

console.log(getRandomBoolean());
// a 50/50 chance of returning true or false
Enter fullscreen mode Exit fullscreen mode

02 - Check if the date is Weekend

By this function, you'll be able to check if the date that is provided is either a weekday or weekend.

const isWeekend = (date) => [0, 6].indexOf(date.getDay()) !== -1;

console.log(isWeekend(new Date(2021, 4, 14)));
// false (Friday)
console.log(isWeekend(new Date(2021, 4, 15)));
// true (Saturday)
Enter fullscreen mode Exit fullscreen mode

03 - Check if a number is even or odd

Simple utility function to check if a number is even or odd.

const isEven = (num) => num % 2 === 0;

console.log(isEven(5));
// false
console.log(isEven(4));
// true
Enter fullscreen mode Exit fullscreen mode

04 - Get the unique values in an array

A very simple method to remove all duplicate values from an array. This function converts our array to a Set and then back to an array.

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

console.log(uniqueArr([1, 2, 3, 1, 2, 3, 4, 5]));
// [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

05 - Check if a variable is an array

A clean and easy way to check if a variable is an array.

Well, there can be other ways too 😉

const isArray = (arr) => Array.isArray(arr);

console.log(isArray([1, 2, 3]));
// true
console.log(isArray({ name: 'Ovi' }));
// false
console.log(isArray('Hello World'));
// false
Enter fullscreen mode Exit fullscreen mode

06 - Generate a random number between two numbers

This will take two numbers as params and will generate a random number between those two numbers!

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

console.log(random(1, 50));
// could be anything from 1 - 50
Enter fullscreen mode Exit fullscreen mode

07 - Generate a random string (unique id?)

Maybe you need to create a temporary unique id for something, here's a trick you can use to generate a random string on the go.

const randomString = () => Math.random().toString(36).slice(2);

console.log(randomString());
// could be anything!!!
Enter fullscreen mode Exit fullscreen mode

08 - Scroll to the top of the page

The window.scrollTo() method takes an x and y coordinate to scroll to.
If we set these to zero and zero, we’ll scroll to the top of the page.

const scrollToTop = () => window.scrollTo(0, 0);

scrollToTop();
Enter fullscreen mode Exit fullscreen mode

09 - Toggle boolean

Toggling a boolean value is one of the very basic programming problems, that can be solved in a lot of different ways.
Instead of using if-statements to determine what value to set the boolean to, you could instead use the function to flip the current value using the ! "not" operator.

// bool is stored somewhere in the upperscope
const toggleBool = () => (bool = !bool);
Enter fullscreen mode Exit fullscreen mode

10 - Swapping Two Variables

The below code is one of the simpler ways to swap two variables without using a third variable and with just one line of code.

[foo, bar] = [bar, foo];
Enter fullscreen mode Exit fullscreen mode

11 - Calculate number of days between two dates

To calculate the days between two dates,
we first find the absolute between two dates and then divide it with 86400000 which is equal to milliseconds in a single day, and at the end, we round the result and return it.

const daysDiff = (date, date2) => Math.ceil(Math.abs(date - date2) / 86400000);

console.log(daysDiff(new Date('2021-05-10'), new Date('2021-11-25')));
// 199
Enter fullscreen mode Exit fullscreen mode

12 - Copy text to clipboard

PS: You might need to add a check to see if navigator.clipboard.writeText exists

const copyTextToClipboard = async (text) => {
  await navigator.clipboard.writeText(text);
};
Enter fullscreen mode Exit fullscreen mode

13 - Different ways of merging multiple arrays

There are a couple of ways to merge arrays. One of them is using the "concat" method. Another one is using the spread operator ("…").

PS: We can also any duplicates from the final array using the "Set" object.

// Merge but don't remove the duplications
const merge = (a, b) => a.concat(b);
// Or
const merge = (a, b) => [...a, ...b];

// Merge and remove the duplications
const merge = [...new Set(a.concat(b))];
// Or
const merge = [...new Set([...a, ...b])];
Enter fullscreen mode Exit fullscreen mode

14 - Get the actual type of javascript primitives

People sometimes use libraries to find the actual type of something in JavaScript, this small trick can save your time (and code size).

const trueTypeOf = (obj) => {
  return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
};

console.log(trueTypeOf(''));
// string
console.log(trueTypeOf(0));
// number
console.log(trueTypeOf());
// undefined
console.log(trueTypeOf(null));
// null
console.log(trueTypeOf({}));
// object
console.log(trueTypeOf([]));
// array
console.log(trueTypeOf(0));
// number
console.log(trueTypeOf(() => {}));
// function
Enter fullscreen mode Exit fullscreen mode

15 - Truncate string at the end

Need to truncate string from the end, not a problem!

const truncateString = (string, length) => {
  return string.length < length ? string : `${string.slice(0, length - 3)}...`;
};

console.log(
  truncateString('Hi, I should be truncated because I am too loooong!', 36),
);
// Hi, I should be truncated because...
Enter fullscreen mode Exit fullscreen mode

16 - Truncate string from the middle

How about truncating the string from the middle?

This function will take a string as the first param, then the size of string we need as 2nd argument, then how many chars we need from the start and end in 3rd and 4th param.

const truncateStringMiddle = (string, length, start, end) => {
  return `${string.slice(0, start)}...${string.slice(string.length - end)}`;
};

console.log(
  truncateStringMiddle(
    'A long story goes here but then eventually ends!', // string
    25, // total size needed
    13, // chars to keep from start
    17, // chars to keep from end
  ),
);
// A long story ... eventually ends!
Enter fullscreen mode Exit fullscreen mode

17 - Capitalizing a string

Well, unfortunately, JavaScript does not have a built-in function to capitalize string, but this workaround can help you obtain the goal.

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

console.log(capitalize('hello world'));
// Hello world
Enter fullscreen mode Exit fullscreen mode

18 - Check if the current tab is in view/focus

This simple helper method returns true or false depending on if a tab is in view/focus

const isTabInView = () => !document.hidden;  // Not hidden

isTabInView();
// true/false
Enter fullscreen mode Exit fullscreen mode

19 - Check if the user is on an Apple device

This will return true if the user is on an Apple device

const isAppleDevice = () => /Mac|iPod|iPhone|iPad/.test(navigator.platform);

console.log(isAppleDevice);
// true/false
Enter fullscreen mode Exit fullscreen mode

20 - The Ternary Operator

This is a great code saver when you want to write an if..else statement in just one line.

// Longhand
const age = 18;
let greetings;

if (age < 18) {
  greetings = 'You are not old enough';
} else {
  greetings = 'You are young!';
}

// Shorthand
const greetings = age < 18 ? 'You are not old enough' : 'You are young!';
Enter fullscreen mode Exit fullscreen mode

Bonus - Short-circuit Evaluation Shorthand

When assigning a variable value to another variable, you may want to ensure that the source variable is not null, undefined, or empty.
You can either write a long if statement with multiple conditionals, or use a short-circuit evaluation.

// Longhand
if (name !== null || name !== undefined || name !== '') {
  let fullName = name;
}

// Shorthand
const fullName = name || 'buddy';
Enter fullscreen mode Exit fullscreen mode

That's all folks! Hope you found this helpful, do not forget to add your email to the mailing list on my website 😉

Discussion (26)

Collapse
moopet profile image
Ben Sinclair

09 Toggle boolean

const toggleBool = (bool) => (bool = !bool);
Enter fullscreen mode Exit fullscreen mode

This could be simplified to

const toggleBool = b => !b;
Enter fullscreen mode Exit fullscreen mode

because you're not actually toggling the original boolean. I'm not sure it offers any benefit beyond using !b in the first place, though.

const uniqueArr = (arr) => [...new Set(arr)];
Enter fullscreen mode Exit fullscreen mode

I think that if you're going to use full words elsewhere, like isArray you should use it here, and make the function uniqueArray. Most of the time, I think if what you're wanting is a set, you should use it as a set. In those cases you probably don't need to convert it back to an array anyway!

To calculate the days between two dates,
we first find the absolute between two dates and then divide it with 86400000 which is equal to milliseconds in a single day

Except... days aren't always 86400 seconds long, and this will fail when times are close to daylight savings, for example. There's a reason date libraries are complicated :)

Collapse
ovi profile image
Muhammad Ovi Author

Woah, man!
This is really helpful, I appreciate your effort <3

Collapse
aminnairi profile image
Amin

Hi there, really cool one-liners! My favorite is the true type one. I actually use it in almost all of my projects.

I'm not sure about the isArray though. This is indeed a one-liner, but in my opinion, it does not add much, besides being a shorter named version of the verbose Array.isArray. Wrapping a function that does exactly what you want with another function seems overkill to me. Don't you think?

Otherwise, great job!

Collapse
matthewadams profile image
Collapse
andreykalechev profile image
Leechy

nope:

typeof []
// "object"
Enter fullscreen mode Exit fullscreen mode
Thread Thread
matthewadams profile image
Matthew Adams

An array is an object. Whether it's an Array is a separate question. I suppose if trueTypeOf were documented, describing its semantics, it would be clearer. Remember, all, syntax doesn't convey everything. You also need semantics. :)

Collapse
ovi profile image
Muhammad Ovi Author

Yeah, sometimes it's handy to just call a function to check, rather than doing Array.isArray(arr) you know.

Collapse
galoelmer profile image
Collapse
robinbastiaan profile image
Robin Bastiaan

Can you explain what this does and where you can put this in practice?

Thread Thread
galoelmer profile image
galoelmer

Check out this post for possible case use:
dev.to/cherif_b/using-javascript-t...

Collapse
matthewadams profile image
Matthew Adams

Um, why write trueTypeOf when you can just use the typeof operator?

typeof 'foobar' === 'string' // returns true
Enter fullscreen mode Exit fullscreen mode
Collapse
ovi profile image
Muhammad Ovi Author

This is helpful if we need to verify if 'foobar' is a string, but in some cases, we want to get the type instead of checking (verifying).

Collapse
djkim profile image
DJ Kim

Awesome article!
A couple suggestions though:

const isTabInView = () => !document.hidden; // Not hidden

and

const isAppleDevice = () => /Mac|iPod|iPhone|iPad/.test(navigator.platform); // to be a function like other examples

Collapse
ovi profile image
Muhammad Ovi Author • Edited

Missed it there, thanks for the suggestions!
Made changes accordingly.

Collapse
chriskingwebdev profile image
ChrisKingWebDev

Be careful not to go too crazy with one liners. If you or a team mate has to dig back into the code after 6 months or a couple years, it can take some brain power to parse out what is happening.

If you are using a build process, the code is going to be minified and optimized in ways that are basically illegible to humans.

Code readability is my primary metric for good work.

Collapse
ovi profile image
Collapse
johandalabacka profile image
Johan Dahl

15 and 16 doesn't work with multi character emojis

> truncateString('Hello 😀 How are you?', 10)
'Hello �...'
Enter fullscreen mode Exit fullscreen mode

You could use Array.from first to convert the string into an array of strings each holding a single character

const truncateString = (string, length) => {
  const chars = Array.from(string)
  return chars.length < length ? string : `${chars.slice(0, length - 3).join('')}...`;
};
Enter fullscreen mode Exit fullscreen mode

This will work correctly

> truncateString('Hello 😀 How are you?', 10)
'Hello 😀...'
Enter fullscreen mode Exit fullscreen mode
Collapse
jonrandy profile image
Jon Randy
const isEven = i=>!(i%2)
Enter fullscreen mode Exit fullscreen mode
Collapse
ovi profile image
Muhammad Ovi Author • Edited

That's good. But it will return true if we call it with no argument

Collapse
phuocng profile image
Phuoc Nguyen

Thanks for sharing. I always think these 1-liners are useful, so I made this site 1loc.dev.
Hopefully it's useful for you as well.

Collapse
ansonznl profile image
九旬

Hello, your article is great. Can I translate it to Chinese community website? I will indicate the source and author.

Collapse
ovi profile image
Muhammad Ovi Author

I would love it 😉

Collapse
johnbo100 profile image
John Jones

Very useful. thank you

Collapse
ovi profile image
Muhammad Ovi Author

Glad you liked it <3

Collapse
frondor profile image
Federico Vázquez

In code reviews, I won't ever call someone a "pro" because he/she writes "one-liners". All the opposite.

Collapse
ovi profile image
Forem Open with the Forem app