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

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 (25 + 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.


1 – Get a random boolean

Using the Math.random() method, this function will produce a boolean (true or false). Math.random generates a random number between 0 and 1, which is then compared to 0.5 to see if it is higher or lower. This means that you have a 50/50 probability of getting true or false.

const getRandomBoolean = () => Math.random() >= 0.5;
console.log(getRandomBoolean());// a 50/50 chance of returning true or false

2 – 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)

3 – 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));// falseconsole.log(isEven(4));// true

4 – Get the unique values in an array

A easiest way for removing duplicate values from an array. Our array is converted to a Set and then returned to an array using this function.

const uniqueArr = (arr) => [...new Set(arr)];
console.log(uniqueArr([1, 2, 3, 1, 2, 3, 4, 5]));// [1, 2, 3, 4, 5]

5 – Shuffle an Array

Shuffling an array is super easy with sort and random methods.

const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());

console.log(shuffleArray([1, 2, 3, 4]));
// Result: [ 1, 4, 3, 2 ]

6 – Detect Dark Mode

Check if a user’s device is in dark mode with the following code.

const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches

console.log(isDarkMode) // Result: True or False

7 – 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]));// trueconsole.log(isArray({ name: 'Ovi' }));// falseconsole.log(isArray('Hello World'));// false

8 – Generate a random number between two numbers

This function will take two numbers as inputs and generate a random number between them!

const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
console.log(random(1, 50));// could be anything from 1 - 50

9 – Generate a random string (unique id?)

If you need a temporary unique id for something, here’s a technique for generating a random string on the go.

const randomString = () => Math.random().toString(36).slice(2);
console.log(randomString());// could be anything!!!

10 – 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();

11 – Toggle boolean

Toggling a boolean value is a fundamental programming topic that can be approached in a variety of ways. You could use the function to flip the current value using the! “not” operator instead of using if-statements to determine what value to set the boolean to.

// bool is stored somewhere in the upperscopeconst toggleBool = () => (bool = !bool);

12 – Swapping Two Variables

One of the simplest ways to swap two variables without needing a third variable and with only one line of code is to use the code below.

[foo, bar] = [bar, foo];

13 – Calculate number of days between two dates

To calculate the number of days between two dates, we first calculate the absolute difference between them, then divide it by 86400000, which is the number of milliseconds in a single day, before rounding the result and returning 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

14 – Check if a number is even or odd

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

console.log(isEven(2)); 
// Result: True

15 – Find Average of Numbers

Find the average between multiple numbers using reduce method.

const average = (...args) => args.reduce((a, b) => a + b) / args.length;

average(1, 2, 3, 4);
// Result: 2.5

16 – Scroll to Top

You can use window.scrollTo(0, 0) method to automatic scroll to top. Set both x and y as 0.

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

goToTop();

17 – 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);};

18 – 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 duplicationsconst merge = (a, b) => a.concat(b);// Orconst merge = (a, b) => [...a, ...b];
// Merge and remove the duplicationsconst merge = [...new Set(a.concat(b))];// Orconst merge = [...new Set([...a, ...b])];

19 – 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(''));// stringconsole.log(trueTypeOf(0));// numberconsole.log(trueTypeOf());// undefinedconsole.log(trueTypeOf(null));// nullconsole.log(trueTypeOf({}));// objectconsole.log(trueTypeOf([]));// arrayconsole.log(trueTypeOf(0));// numberconsole.log(trueTypeOf(() => {}));// function

20 – 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...

21 – Truncate string from the middle

Why not cut the string right in the middle?
This function will take a string as the first parameter, the size of the string as the second argument, and the number of characters from start to end as the third and fourth arguments.

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!

22 – 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

23 – 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

24 – 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

25 – The Ternary Operator

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

// Longhandconst age = 18;let greetings;
if (age < 18) {  greetings = 'You are not old enough';} else {  greetings = 'You are young!';}
// Shorthandconst greetings = age < 18 ? 'You are not old enough' : 'You are young!';

Bonus – Short-circuit Evaluation Shorthand

If you’re going to assign a variable value to another variable, make sure the source variable isn’t null, undefined, or empty. You can either utilize a short-circuit evaluation or create a long if statement with several conditionals.

// Longhandif (name !== null || name !== undefined || name !== '') {  let fullName = name;}
// Shorthandconst fullName = name || 'buddy';

That’s all folks! Hope you found this helpful, see you in the next one 😉

Leave a Comment