Zoom Webinar: Learn and enhance your TypeScript skills | 28th March 2023 | 10 AM PST [10:30 PM IST] Register here

12 Life-Saving JavaScript One-Liners to Boost Up Your Productivity



August 8, 2022


August 8, 2022

How can you code less and achieve more? 

There can be multiple ways, but here we are going to cover the unique way that most developers love to use. 

“JavaScript One-Liner!”🤘

JavaScript is a wonderful language that lets you do amazing things from developing frontend to backend and handling complex APIs. But beyond that, it also facilitates creating awesome stuff just using a single line of code.🥰

Don’t you think it's always cool to learn new things? 

So get familiar with the 12 JavaScript OneLiners to boost up your JS app development productivity. 

Let's get started! 🚀

1. Checking variables in an array

The easiest way to check variables in an array.

const isArray = (arr) => Array.isArray(arr);
console.log(isArray([1, 2, 3]));
// true
console.log(isArray({ name: 'Sara' }));
// false
console.log(isArray('Hello World'));
// false

2. Generating the random string

When you want to create a temporary unique id for authentication or anything else, here is how you can make it.

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

3. Capitalizing a string

You can use the code in the snippet to capitalize input. 

const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
console.log(capitalize('follow for more')); // Follow For More

4. Calculating the number of days between two dates

To calculate the number of days between two dates,  find the absolute between two dates and then divide it by 86400000 (milliseconds in a single day) at the end of the day we will round the result and return the output.

const daysDiff = (date, date2) => Math.ceil(Math.abs(date - date2) / 86400000);
console.log(daysDiff(new Date('2022-05-10'), new Date('2022-11-25'))); // 199

5. Shuffling an array

Shuffling two arrays using 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. Reverse a String

To reverse a string you can use the split, reverse and join method. 

const reverse = str => str.split('').reverse().join('');
reverse('Hello World');    // Result: 'dlroW olleH'

7. Merging an Array

You can merge an array using the “concat” method, the spread [“...”]operator and finally, we can use the Set object to remove any duplicate.

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

8. Truncating the string from the middle

What if you want to truncate the string from the Middle?

The function will take the string as the first parameter, length as the second, and start and end as the third and fourth parameters.

const truncateStringMiddle = (string, length, start, end) => {
  return `${string.slice(0, start)}...${string.slice(string.length - end)}`;
      '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!

9. Truncate string at the end

It's super easy to truncate strings.

const truncateString = (string, length) => {
    return string.length < length ? string : `${string.slice(0, length - 3)}...`;
  console.log(truncateString('Truncate the string because, its too long', 30));
   // Truncate the string because...

10. Wait for certain time before execution

In asynchronous programming, if you want to wait for a certain amount of time, here is the way you can do that.

const wait = async (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
const test = async () => {await wait(1000)
  console.log("waited for 1 second.")          
// the output will be generated after 1000 milliseconds.

11. Convert string to a URL slug

Convert your String to URL using Regular expression that will remove the special characters and add “-” in between the words.

const slugify = string => string.toLowerCase().replace(/\s+/g, '-').replace(/[^\w-]+/g, '');   // Example
console.log(slugify('Lifesaving JavaScript OneLiners')); 
// Result:lifesaving-javascript-oneliners

12. Get the value of Cookie

Nowadays every website uses cookies. You can get the value of a specific cookie that you want to know using the following function.

const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();
console.log(cookie('_ga')); // Result: GA1.1.1556710793.1646367473

There is no doubt JavaScript OneLine improves developers' productivity, but as we know it's not the only way to achieve it.

Let's find out how we can help you to improve your full-stack JavaScript app development efficiency with the revolutionary app development platform.

DhiWise: A developer-centric platform to build enterprise-grade apps in the fastest way.”

Whether you are a frontend or backend JavaScript developer DhiWise offers you everything to make your app development a breeze. 

Here are some of the functionalities of DhiWise that you must look into.

  1. DhiWise Figma to Code(React.js, Kotlin, Flutter, and Swift). 
  2. Supports Front end technologies such as React.js, and Flutter.
  1. Support backend Technologies such as Node.js and Laravel for PHP.
  2. Supports full-stack development technologies like JavaScript, Swift, and Kotlin.
  3. Generates clean Code, simplifying code maintenance and improving scalability.
  4. Logic builder to create app-specific workflows from scratch.
  5. Integrated with Firebase and Superbase.
  6. The platform offers a complete code view and flexibility to make changes at any time during development and once the app is built.
  7. Simplified team collaboration, code sharing, and management. 

If you are still not assured about DhiWise capabilities, just try it, we have made sure that you will always find it super easy and fast to code. 

So enjoy coding!

Summing up:

That's all, I hope you enjoyed the article. Now you know about the 12 javaScript OneLiner + functionalities of DhiWise. Don’t forget to check out our other medium articles here.

Have a nice day!