DEV Community

Cover image for 20 Must-Know JavaScript Utility Functions to Boost Productivity
Shubham Tiwari
Shubham Tiwari

Posted on • Edited on

6 2 2 2 1

20 Must-Know JavaScript Utility Functions to Boost Productivity

Hello my frontend developer friends, today i will be sharing some useful utilities to avoid repeating code and boost productivity. These snippets are often used in many projects and saves a lots of time doing the same thing again and again in multiple files.

  • I'll be creating my code snippets on Scribbler.live first, which is a fantastic platform that allows you to run a JavaScript Notebook, Online Compiler, and Editor without the need for manual setup.
  • Additionally, I am including a link to code snippets that includes all of the code examples so you can open the snippet and run it yourself to see the results.
  • I will be using scrib.show from scribbler.live, it is equivalent to console.log

Code. Hack. Win. Every Idea Starts with a Scribble.

Join the Summer of Scribbling 2025 — a 15-day online JavaScript hackathon where creativity meets code. From AI to XR, build innovative projects using Scribbler's browser-based JavaScript notebooks. Compete for exciting prizes, including Android tablets and internship opportunities. Registration is now open.

Lets dive in...
Table of contents

1. Generate a random integer between min and max

It is useful if you want to create a random id for some object in the data.

// 1. Generate a random integer between min and max
const randomInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
scrib.show(randomInt(100,100000))
Enter fullscreen mode Exit fullscreen mode

2. Get time ago (e.g., "4 hours ago")

It is useful to show when a person was online in a chat app or could be used to show when a file was last updated.

// 2. Get time ago (e.g., "4 hours ago")
const timeAgo = date => {
  const diff = (new Date() - new Date(date)) / 1000;
  const units = [
    ['year', 31536000], ['month', 2592000],
    ['day', 86400], ['hour', 3600],
    ['minute', 60], ['second', 1]
  ];
  for (let [unit, sec] of units) {
    const val = Math.floor(diff / sec);
    if (val >= 1) return `${val} ${unit}${val > 1 ? 's' : ''} ago`;
  }
  return 'just now';
};
scrib.show(timeAgo("2025/05/12"))
Enter fullscreen mode Exit fullscreen mode

3. Format date to YYYY-MM-DD

It is useful to convert the date coming from an api to yyyy-mm-dd format for UI.

// 3. Format date to YYYY-MM-DD 
const formatDate = date => new Date(date).toISOString().split('T')[0];
scrib.show(formatDate("2025/05/12"))
Enter fullscreen mode Exit fullscreen mode

4. Remove duplicates

It could be used to remove duplicate values from an array to make it valid and corrected.

// 4. Remove duplicates
const unique = arr => [...new Set(arr)];
scrib.show(unique([1,1,2,2,2,3,4,5,5,9]))
Enter fullscreen mode Exit fullscreen mode

5. Flatten nested arrays

It could be used to flatten a multi dimensional array to single level array to map over its values.

// 5. Flatten nested arrays
const flatten = arr => arr.flat(Infinity);
scrib.show(flatten([1,1,[2,2,2],[3,4,[5]],5,9]))
Enter fullscreen mode Exit fullscreen mode

6. Shuffle array

It could be used to shuffle the UI list every time a user visit the page.

// 6. Shuffle array
const shuffle = arr => arr.sort(() => Math.random() - 0.5);
scrib.show(shuffle([1,1,2,2,2,3,4,5,5,9]))
Enter fullscreen mode Exit fullscreen mode

7. Get the intersection of two arrays

It could be used to compare 2 lists for a difference.

// 7. Get the intersection of two arrays
const intersect = (a, b) => a.filter(x => b.includes(x));
scrib.show(intersect([1,2,3,4],[1,3,4,5]))
Enter fullscreen mode Exit fullscreen mode

8. Capitalize first letter

Captilizing the first letter of the word in UI

// 8. Capitalize first letter
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);
scrib.show(capitalize("mysterio"))
Enter fullscreen mode Exit fullscreen mode

9. Slugify a string to create a hyphenated url slug

Creating a hyphenated slug for the url from strings.

// 9. Slugify a string to create a hyphenated url slug
const slugify = str => str.toLowerCase().trim().replace(/\s+/g, '-').replace(/[^\w\-]+/g, '');
scrib.show(slugify("products and services")) // products-and-services
Enter fullscreen mode Exit fullscreen mode

10. Truncate a string

It could be used for adding elipsis in UI after a speicific word count reaches in the content

// 10. Truncate a string
const truncate = (str, len) => str.length > len ? str.slice(0, len) + '...' : str;
scrib.show(truncate("Web development has many frameworks", 25))
Enter fullscreen mode Exit fullscreen mode

11. Validating an email

It could be used to validate an email and return a boolean whether the text passes the validation

// 11. Validating an email
const isEmail = str => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(str); // replace regex with your regex
scrib.show(isEmail("mysterio09@gmail.com"))
Enter fullscreen mode Exit fullscreen mode

12. Check if an object is empty

It could be used to add a conditional to check for the empty objects before proceeding with the actual logic.

// 12. Check if an object is empty
const isEmptyObject = obj => Object.keys(obj).length === 0;
scrib.show(isEmptyObject({})) // true
scrib.show(isEmptyObject({ name: "Mysterio" })) // false
Enter fullscreen mode Exit fullscreen mode

13. Get query params from URL

Extracting out query params from url to an object

// 13. Get query params from URL
const getQueryParams = url => Object.fromEntries(new URL(url).searchParams.entries());
const url = "https://example.com/user?name=mysterio&age=24&country=India";
scrib.show(getQueryParams(url)) // { "name": "mysterio", "age": "24", "country": "India" }
Enter fullscreen mode Exit fullscreen mode

14. Serialize object to query string

This is the opposite of above example, here we create a query param from an object.

// 14. Serialize object to query string
const toQueryString = obj => new URLSearchParams(obj).toString();
const person = { "name": "mysterio", "age": "24", "country": "India" }
scrib.show(`https://example.com/user?${toQueryString(person)}`)
Enter fullscreen mode Exit fullscreen mode

15. Checking for leap year

It could be used in the logic where we are applying conditions based on number days like a discount.

// 15. Checking for leap year
const isLeapYear = year => new Date(year, 1, 29).getDate() === 29;
scrib.show(isLeapYear("2025-05-15"))
Enter fullscreen mode Exit fullscreen mode

16. Remove Falsy Values

Removing falsy values like false, undefined, 0, null, "", etc.

// 16. Remove Falsy Values
const compact = arr => arr.filter(Boolean);
scrib.show(compact([false, undefined, null, 0, 1, 2, 3]))
Enter fullscreen mode Exit fullscreen mode

17. Count Occurrences in Array

Categorising values in an array for more than 1 occurence.

// 17. Count Occurrences in Array
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
scrib.show(countOccurrences([1,1,2,2,2,3,4,5,5,9], 2))
Enter fullscreen mode Exit fullscreen mode

18. Find Duplicates in Array

Find duplicates value in an array

// 18. Find Duplicates in Array
const findDuplicates = arr => {
  return [...new Set(arr.filter((item, index) => arr.indexOf(item) !== index))];
};
scrib.show(findDuplicates([1,1,2,2,2,3,4,5,5,9]))
Enter fullscreen mode Exit fullscreen mode

19. Check if Value is Numeric

Useful when we want to add a conditional to check for the type of value and proceed doing numeric calculations if the value is numeric.

// 19. Check if Value is Numeric
const isNumeric = val => !isNaN(parseFloat(val)) && isFinite(val);
scrib.show(isNumeric(NaN)) // false
scrib.show(isNumeric("24s")) // false
scrib.show(isNumeric("24")) // true
scrib.show(isNumeric(24)) // true
scrib.show(isNumeric(24.45)) // true
Enter fullscreen mode Exit fullscreen mode

20. Pick specific keys from an object

Useful when you don't want the entire object and want only specific parts of it

// 20. Pick specific keys from an object
const pick = (obj, keys) =>
  keys.reduce((acc, key) => {
    if (key in obj) acc[key] = obj[key];
    return acc;
  }, {});
const person = { "name": "mysterio", "age": "24", "country": "India" }
scrib.show(pick(person, ["name", "age"]))
Enter fullscreen mode Exit fullscreen mode

That's it for this post, Let me know if i could do any improvements in this article. Also, do check Scribbler.live website.

You can contact me on -

Instagram - https://www.instagram.com/supremacism__shubh/
LinkedIn - https://www.linkedin.com/in/shubham-tiwari-b7544b193/
Email - shubhmtiwri00@gmail.com

You can help me with some donation at the link below Thank you👇👇
https://www.buymeacoffee.com/waaduheck

Also check these posts as well

ACI image

ACI.dev: Best Open-Source Composio Alternative (AI Agent Tooling)

100% open-source tool-use platform (backend, dev portal, integration library, SDK/MCP) that connects your AI agents to 600+ tools with multi-tenant auth, granular permissions, and access through direct function calling or a unified MCP server.

Star our GitHub!

Top comments (1)

Collapse
 
dotallio profile image
Dotallio •

Always love posts that give you instant copy-paste helpers like these, perfect for building quick MVPs or prototypes. Do you have a favorite snippet you use every day?